문제

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