I have a small html code base that produces a list of unique links, I want to get each an every link's text value using java script (not the link only the text).
my sample code (doesn't work)
for (var x = 0; x < document.getElementById("folderLink").length; x++) {
alert(document.getElementById("folderLink")[x].innerHtml);
}
HTML
<a id="folderLink" href="somelink">Dynamic Text Text Text</a>
assume that this is a one link of the list.
Thanks.
getElementById will only ever return one element, regardless of how many there may be with that ID. Because there should only ever be one element of any ID.
So you can't access its length because it's not a collection it's a DOM node.
You could use getElementsByClassName
Related
I am trying to changing anchor, id, span or b tag text color, but it's not changing because of randomly changing id.
Here is the HTML Code:
<a id="XgP7Wrq-1503732157576" tabindex="-1" href="javascript:void(0);" style=""><span class="thin">here</span> <b>sometext</b></a>
Here is the JS Code:
var x = getElementsbyid("XgP7Wrq-1503732157576");
x.style.color = '#00FF00';
else if any alternative way to achieve this?
Thanks
If you are traversing the DOM with ID, the correct syntax is as follows,
var x = document.getElementById("XgP7Wrq-1503732157576");
x.style.color = "#00FF00";
You do not include the hashtag as argument because the method specifically looks for the ID.
Since the ID of the elements is always changing, you may do one of the followings too.
// Accessing the third <a> element
var x = document.getElementsByTagName("a")[2]
// Accessing the first element with class "apple"
var x = document.getElementsByClassName("apple")[0]
Try using the class
<a id="XgP7Wrq-1503732157576" class="myclass" tabindex="-1" href="javascript:void(0);" style=""><span class="thin">here</span> <b>sometext</b></a>
Code js:
var x = document.getElementsByClassName("myclass");
//for first anchor
x[0].style.color = "#00FF00";
//for all
for(var i=0; i<= x.length; i++)
{
x[i].style.color = "#00FF00";
}
You'll have to find some other way to identify it, based on something that doesn't change. You haven't given us enough information for us to help you do that, but some ways are
Where it is in the structure of the page, a compound selector could find it. For instance, if it were the first a element with href="javascript:void(0)" that's inside a div with class header, then document.querySelector("div.header a[href='javascript:void(0)']") would find it. Or if that span.thin is consistent, then document.querySelector("a > span.thing").parentNode.
If there's something about the id that doesn't change, an attribute substring selector could work (document.querySelector("a[href*='substring']")).
If it's always the 4th (or whatever) a element with href="javascript:void(0)", you could find it based on that (document.querySelectorAll("a[href*='javascript:void(0)']")[3]).
...etc. The tools are:
document.getElementById - But you'd have to know its id, so that's out.
document.querySelector - Find the first element that matches the given CSS selector. Can be a full selector, including a compound one. Any valid CSS selector works.
document.querySelectorAll - Finds all elements that match the given CSS selector (as a list).
I have multiple elements on a page with the same class name, but each element has a unique id name.
Example:
<div class="video-image" id="get-googled">
<div class="video-image" id="email-marketing">
I want to display the id value, but right now I am only able to have GTM return and display the first element on the page. I read this post: "Getting value of ID from class" and it didn't help and even explains doing it the simple way will only display the first elements value.
Do I need custom Javascript to create this properly?
If you want to get a specific div and you know where it is on the page you might be able to use a DOM variable with an nth of type query selector. But this seems cumbersome, and since it seems you want a list in any case I think you are better of with a custom javascript variable:
function() {
return document.querySelectorAll(".video-image");
}
which return a collection of DOM elements (you might want to check if there are actually elements with that class first).
The initial answer is the right start - this completes the loop:
<script>
var inputs = document.querySelectorAll(".video-image");
for (var i = 0; i < inputs.length; i++) {
alert(inputs[i].id);
}
</script>
Here is a JSFiddle to try it out - [https://jsfiddle.net/JMurphy22/kduybmsp/2/][1]
I can use the following to create a indexed list of each instance of a particular item in a class.
var x = document.getElementsByClassName("page");
I can use the following to direct users to a particular id:
function CalledBySelectBox(value)
{
document.getElementById(value).scrollIntoView();
}
However, the elements I want to direct users to are not uniquely identified with Id's. How do I modify the second snippet above, to direct users to a particular instance/occurrence of x in the first snippet. Or to put it differently, how do I direct them to a particular instance of the class.
If its helpful, here is some sample html:
Some text of unknown length full of random tags and what have you.<span class="page">104</span> A bunch more text but we don't know how much and full of other tags.<span class="page">105</span> Some text of unknown length full of random tags and what have you <span class="page">106</span>
I think you are looking for something like this:
function ScrollToPage( page_num )
{
document.getElementsByClassName( 'page' )[ page_num ].scrollIntoView();
}
What getElementsByClassName(className) gives you is an array of elements, what document.getElementById(id) gives you is a single element. To scroll to an indexed element in the array you get, just call scrollIntoView() on that element.
var x = document.getElementsByClassName("page");
x[5].scrollIntoView();
I would like to scan a page for all DOM elements of type HTMLButtonElement so that I can get their exact position. I would then use this position to place another button on top.
I've been scanning through all DOM elements by the following code snippet:
var all = document.getElementsByTagName("*");
var temp = document.createElement('button');
for (var i = 0, max = all.length; i < max; i++) {
//Loop through all[i] to see if it is an object of type HTMLButtonElement
}
As already pointed out in comments, you can simply use:
document.getElementsByTagName("button");
The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself. The returned list is live, meaning that it updates itself with the DOM tree automatically. Consequently, there is no need to call several times Element.getElementsByTagName() with the same element and arguments.
– MDN's article on Element.getElementsByTagName()
Be aware though that HTML also has the <input type="button" /> element as well. If you want to pull these as well, you'd be better off using document.querySelectorAll() which allows us to specify multiple comma-delimited selectors:
document.querySelectorAll('button, input[type=button]');
Furthermore, you can also define button behaviour on elements by setting the ARIA attribute role to "button":
<div role="button">...</div>
If you also want to pull these, you can also include [role=button] in the above querySelectorAll call.
what's the different between using:
// assuming using elements/tags 'span' creates an array and want to access its first node
1) var arrayAccess = document.getElementsByTagName('elementName')[0]; // also tried property items()
vs
// assuming I assign an id value to the first span element/tag
// specifically calling a node by using it's id value
2) var idAccess = document.getElementById('idValue');
then if I want to change the text node....when using example 1) it will not work, for example:
arrayAccess.firstChild.nodeValue = 'some text';
or
arrayAccess.innerText/innerHTML/textContent = 'some text';
If I "access" the node through its id value then it seems to work fine....
Why is it that when using array it does not work? I'm new to javascript and the book I'm reading does not provide an answer.
Both are working,
In your first case you need to pass the tag name instead of the element name. Then only it will work.
There might be a case that you trying to set input/form elements using innerHTML. At that moment you need to use .value instead of innerHTML.
InnerHTML should be used for div, span, td and similar elements.
So your html markup example:
<div class="test">test</div>
<div class="test">test1</div>
<span id="test">test2</span>
<button id="abc" onclick="renderEle();">Change Text</button>
Your JS code:
function renderEle() {
var arrayAccess = document.getElementsByTagName('div')[0];
arrayAccess.innerHTML = "changed Text";
var idEle = document.getElementById('test');
idEle.innerHTML = "changed this one as well";
}
Working Fiddle
When you use document.getElementsByTagName('p'), the browser traverses the rendered DOM tree and returns a node list (array) of all elements that have the matching tag.
When you use document.getElementById('something'), the browser traverses the rendered DOM tree and returns a single node matching the ID if it exists (since html ID's are unique).
There are many differences when to use which, but one main factor will be speed (getElementById is much faster since you're only searching for 1 item).
To address your other question, you already have specified that you want the first element in the returned nodeList (index [0]) in your function call:
var arrayAccess = document.getElementsByTagName('elementName')[0];
Therefore, arrayAccess is already set to the first element in the returned query. You should be able to access the text by the following. The same code should work if you used document.getElementById to get the DOM element:
console.log(arrayAccess.textContent);
Here's a fiddle with an example:
http://jsfiddle.net/qoe30w2w/
Hope this helps!