I'm trying to write a simple script which will change the text of a number of anchors on a page. I'm quite new to Javascript and I'm able to change the anchors but it changes the whole tag including removing the href.
How do I edit just the text only without affecting the href?
<body>
<div class="loop-add-to-cart">
Add to basket
<div class="wpd-buttons-wrap-simple" data-id="11544">
Design from blank
</div>
</div>
<script>
function buybuttons() {
var buybuttons = document.getElementsByClassName('wpd-buttons-wrap-simple');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].innerHTML="Test";
};
}
buybuttons();
</script>
</body>
You can use a query selector to get all a tags inside an element with a class of wpd-buttons-wrap-simple:
document.querySelectorAll('.wpd-buttons-wrap-simple a');
You can then set the textContent or innerHTML of the link.
<body>
<div class="loop-add-to-cart">
Add to basket
<div class="wpd-buttons-wrap-simple" data-id="11544">
Design from blank
</div>
</div>
<script>
function buybuttons() {
var buybuttons = document.querySelectorAll('.wpd-buttons-wrap-simple a');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].textContent = "Test";
};
}
buybuttons();
</script>
</body>
Using 'querySelectorAll' you can get the element the class and the element inside as below:
document.querySelectorAll('.wpd-buttons-wrap-simple > a')
function buybuttons() {
var buybuttons = document.querySelectorAll('.wpd-buttons-wrap-simple a');
for(var i = 0; i < buybuttons.length; i++){
buybuttons[i].innerHTML="Test";
};
}
buybuttons();
You are currently overwriting the innerHTML of the div element, but you are looking for the anchor element inside of the div.
Use document.querySelectorAll to get all of them, or document.querySelector to only get the first.
Related
I want to select all the <"a"> tags on a page that are inside all the <"code"> tags on the page so I can count them, and I want to do this using JavaScript.. how can I do this?
I tried using document.getElementsByTagName("code").getElementsByTagName("a"); and document.getElementsByTagName("code").querySelectorAll("a"); but it doesn t seem to work
document.getElementsByTagName("code").getElementsByTagName("a");
VM1278:1 Uncaught TypeError: document.getElementsByTagName(...).getElementsByTagName is not a function
at :1:39
You can use .querySelectorAll(selectors).
const matches = document.querySelectorAll('code a');
console.log(matches);
<code>
<a>Test</a>
<p>Other tag</p>
<a>Example</a>
</code>
You need to loop through the initial element search, since it returns an HTMLCollection of elements:
var elements = document.getElementsByTagName("code");
var all = [];
for(var i = 0; i < elements.length; i++){
var tempElements = elements[i].getElementsByTagName("a");
all = [...tempElements, ...all];
}
Try this instead:
document.querySelectorAll('code a').length
The querySelector and querySelectorAll functions accept CSS-like DOM selectors and return a node or NodeList, respectively.
See:
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
You can use
document.querySelector("code > a");
you can do it like this:
var anchors = document.getElementById("thediv").getElementsByTagName("a");
alert("The Div has " + anchors.length + " links in it");
<div id="thediv">
link 1
link 2
link 3
</div>
Here, I have two div on my webpage both div have almost same data.
accept type attribute.
My first div attribute have type="timeline".
and Second div attribute type ="slideshow".
When my page load it only detects the first div.
But I have a condition if my div type equal to slideshow then my code run but it detects only first div.
Here is my code.
<div type='timeline' id='slide'>
<section>
<header>Title One</header>
<article>Content</article>
</section>
<section>
<header>Title Two</header>
<article>Content</article>
</section>
<section>
<header>Title Three</header>
<article>Content</article>
</section>
<section>
<header>Title Four</header>
<article>Content</article>
</section>
</div>
var divSlide = document.querySelectorAll('#slide');
var myNodeList = divSlide.length;
for(i = 0; i < myNodeList.length; i++) {
var divMain = document.getElementById("slide");
console.log(divMain);
var align = divMain.getAttribute("type");
console.log(align);
console.log(myNodeList)
if(align=='slideshow'){
console.log("my working code");
}
}
What should i do.
Help will be appreciated.
You have a few of mistakes in your code that we need to fix first.
First, you shouldn't use the same id value more than once in your code so you need to replace the id with a class (even though our code can still work with id here).
Second mistake - in your for loop you are using the wrong variable "myNodeList.length", myNodeList variable already is the length so it does not have a length property. you should instead use the divSlide variable like this:
for(i = 0; i < divSlide.length; i++)
Third mistake- in order to access the current item that is being looped over you should use the variable that holds the list (which is divSlide here)and then add to it i in brackets to indicate the current index in use, like this
var divMain = divSlide[i];
// instead of this: var divMain = document.getElementById("slide");
Fourth - you should in most cases use triple = signs to check for values. so instead of == you should use ===
this is how the code will look like finally:
var divSlide = document.querySelectorAll('#slide');
var myNodeList = divSlide.length;
document.addEventListener("DOMContentLoaded", functionName)
function functionName(){
for(i = 0; i < divSlide.length; i++) {
var divMain = divSlide[i];
var align = divMain.getAttribute("type");
if(align ==='slideshow'){
console.log("my working code");
}
}
}
and this is codepen example
You can get div by type attribute like this:
HTML
<div type='timeline' id='slide'>
this is timeline
</div>
<div type='slideshow' id='slide'>
this is slideshow
</div>
JS
$('#slide[type=slideshow]') // get div that has id='slide' and type='slideshow'
Online Demo (jsFiddle)
I have created my own JS library. In that i am trying to define append method like this:
append: function (els) {
var elChild = document.createElement('span');
elChild.innerHTML = els;
for(i = 0; i < this.length; i++){
this[i].appendChild(elChild);
}
}
Now i am calling this append method in my script tag of HTML page like this:
<body>
<h1 class="first_heading">hello</h1>
<h1 class="second_heading">hi</h1>
<button>Test Me</button>
</body>
<script>
dome.get('h1').append('<p>some text</p>');
</script>
But the problem is all h1 tags not appending the paragraph text. Only last h1 is appending paragraph text. Any solution?
https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild:
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position
In other words, the same node can't appear in multiple places in a document. You have to call document.createElement('span') separately for each child you want to create.
As mentioned this this corresponds to the object in scope. In this scenario, it is the window object. Here is a simple way to append the string to all headers
function append(tagname, text) {
// get all tag names
all_t = document.getElementsByTagName(tagname);
// loop through and append the string to the inner html of each tag
for (var x = 0; x < all_t.length; ++x) {
all_t[x].innerHTML += text
}
}
append('h1', '<p>some text</p>')
<h1 class="first_heading">hello</h1>
<h1 class="second_heading">hi</h1>
<button id="b">Test Me</button>
I have a ul tag with an ID and on a click of a button I want to change height and display of the div itself and same for each a tag inside that div.
I have trouble select each a tag and changing their style.
I want to use just javascript.
My mark-up
<ul id="mobile_nav" >
<a href="about.html" class="images" ><li><p>about me</p></li></a>
<li><p>work</p></li>
<li ><p>let's talk</p></li>
</ul>
My js
var but = document.getElementById('mobile_menu')
but.onclick=function() {
var ul = document.getElementById('mobile_nav')
var a = document.getElementById('mobile_nav').getElementsByTagName('a');
console.log(ul) //SEEMS TO WORK
console.log(a) //AS ABOVE
console.log(typeof(a)) // THAT S AN OBJECT
ul.style.display="block" // THAT S WORK
ul.style.height="auto";//WORKING
//TRYING TO GO THOUGHT MY OBJECT AND CHANGE HEIGHT
for (var x in a) {
a[x].style.height="42px";//IT SAID PROPERTY OF UNDEFINED
console.log('done')// IT S PRINTING THAT AS MANY AD MY A TAGS
console.log(a[x].)// NUMBER OF A TAGS IN MY DIV
}
}
As you wrote, you find all elements you are after with:
var elements = document.getElementById('mobile_nav').getElementsByTagName('a');
The result of above is NodeList. You can traverse it like that:
for (var i = 0, len = elements.length; i < len; i++){
elements[i].style.height = "25px";
}
I want to hide the <h1> element using plain javascript, not jQuery, without adding id="whatever" or class="whatever" to the tag. Is this possible?
Why can't I just add id="whatever" to the tag?
I'm using a UIButton in xCode that when clicked, it injects javascript into a UIWebView. Inside that UIWebView is a H1 element that is on a website that I do not have access to to add <h1 id="whatever">. I hope it makes sense.
document.getElementsByTagName('h1')[0].style.display = 'none';
You can use getElementsByTagName method:
var h = context.getElementsByTagName('h1');
for (var i = h.length; i--; ) {
h[i].style.display = 'none';
}
Where context is document or more specific parent node you want to search your headers within.
However there is better solution. You could add specific class to some parent node and hide child headers with CSS:
.without-headers h1 {display: none;}
Use getElementsByTagName to hide the first h1 on your page:
document.getElementsByTagName("h1")[0].style.display = "none";
// ^ index 0, so that's the first `h` that's found.
Or to hide them all:
var headers = document.getElementsByTagName("h1");
for (var i = 0, l = headers.length; i < l; i++; ) {
headers[i].style.display = "none";
}
Or even better yet, if you can modify the CSS:
h1{
display:none;
}
For the JavaScript solutions, please keep in mind that they will only work when the DOM has been loaded.
Add a domready event listener, like this:
window.addEvent('domready', function() {
// modify your DOM here.
});
you can use getElementsByTagName
document.getElementsByTagName("h1")
But it will access all h1 elements, so to be more specific access it by index like this
document.getElementsByTagName("h1")[0].style.display = "none";
just small change in dfsq's code
var h = document.getElementsByTagName('h1');
for (var i =0; i<h.length; i++) {
document.getElementsByTagName('h1').item(i).style.display = 'none';
}