What I ultimately want to do is find a link in a div with a known class name and change it. I'm stuck on properly getting the content of the link and cannot figure out my mistake. Using getElementsByClassName and getElementsByTagName seemed to both work separately but will not work when I use them together. I've never used jquery before so I don't feel fortable going that route.
Here's the code:
<div class="test">
<a href="">LINK</a></div>
<button onclick="myFunction()">Test it</button>
<script>
function myFunction()
{
var x=document.getElementsByClassName("test");
x.getElementsByTagName("a")[0].innerHTML="Hello World";
document.write(x[0]);
};
</script>
What I ultimately want to do is find a link in a div with a known class name and change it. I'm stuck on properly getting the content of the link and cannot figure out my mistake. Using getElementsByClassName and getElementsByTagName seemed to both work separately but will not work when I use them together. I've never used jquery before so I don't feel fortable going that route.
Here's the code:
<div class="test">
<a href="http://www.google.">LINK</a></div>
<button onclick="myFunction()">Test it</button>
<script>
function myFunction()
{
var x=document.getElementsByClassName("test");
x.getElementsByTagName("a")[0].innerHTML="Hello World";
document.write(x[0]);
};
</script>
Share
asked Oct 31, 2013 at 20:18
user2942844user2942844
231 silver badge3 bronze badges
3
- I suspect that solving exactly this kind of problem is actually why jQuery was invented. You may want to reconsider going that route. Otherwise you will need to write a recursive DOM traversal yourself, which is how jQuery does it in old browsers. – Mike Edwards Commented Oct 31, 2013 at 20:22
-
To clarify.
x
is a collection of DOM elements. Collections do not have very many properties. For example, they do not have thegetElementsByTagName
method. That's why your code fails. David Thomas has good solutions. – user2625787 Commented Oct 31, 2013 at 20:27 -
From my limited js/html/whatever knowledge: Don't use
document.write
once the site has loaded. Remove that. – Johannes Kuhn Commented Dec 9, 2013 at 22:55
2 Answers
Reset to default 8In pliant browsers you could simply use document.querySelector()
:
var x = document.querySelector('.test > a');
x.innerHTML = 'Hello world';
document.querySelector
returns a single element (the only element, or the first of multiple elements), rather than a nodeList
/collection (returned by getElementsByTagName()
and getElementsByClassName()
).
Incidentally, with jQuery:
$('.test > a').html('Hello world'); // sets the innerHTML of the returned elements
Or:
$('.test > a').text('Hello world'); // sets the text of the returned elements
Use the query selector syntax as follows:
var x = document.querySelector('div.classname > p');
This will result in all <p>
elements within the div.classname
.