Search code examples
javascriptgetelementsbytagnamegetelementsbyclassname

How to use get elements by class name and then by id in JavaScript?


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 comfortable going that route.

Here's the code:

<div class="test">
<a href="http://www.google.com">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>

Solution

  • In compliant 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