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>
有帮助吗?

解决方案

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 

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top