开发者

adding a new div after another one

I am trying to add a new div right after a div with the class of dtext01 but its not working. Here is what the div looks like with the class <div class="dtext01"></div> and I would like the final code to look like this <div cla开发者_StackOverflow中文版ss="dtext01"></div><div id="rewards">Testing!!!</div>

Here is the code I have tried with no success.

<script type="text/javascript">
var stickyNode = document.createElement("div");

stickyNode.innerHTML = 'Testing!!!';

stickyNode.id = "rewards";
var referenceNode = document.getElementByClass("dtext01");
referenceNode.parentNode.insertBefore(stickyNode, referenceNode);
</script>


There is no document.getElementByClass(). There are document.getElementsByClassName() and querySelectorAll() which can be used for fetching elements by className, but they are not standard across browsers.

You can always import a cross browser getElementsByClassName from a reliable source, such as this one, or write your own - or just use IDs instead of classes if you have a choice.


The function you are looking for is document.getElementsByClassName (note the plural on Elements). It is a fairly recent addition to the HTMLElement interface, so you should test for it and provide a fallback if it isn't supported.

To append your div just after the first node returned, use:

var referenceNode;
if (document.getElementsByClassName) {
    referenceNode = document.getElementsByClassName("dtext01")[0];
} else {
    // fallback to some other function
}

// Make sure you got a node before trying to call methods on it
if (referenceNode) {
    referenceNode.parentNode.insertBefore(stickyNode, referenceNode);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜