Change height to all a element in a div with Javascript - javascript

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";
}

Related

select html element by its full html tag - JS

I am looking for a way to be able to select an HTML element by its tag, like:
document.querySelector("<div id='myDiv'\>hello world</div\>")
//instead of: document.querySelector("#myDiv")
However, this code returns an error. The code should return the HTML element.
Does anybody know a way to achieve this? (vanilla JS preferred)
It seems a bit odd that you wouldn't want to select element via ID. But regardless one way of selecting the element in your example would be to look for its innerHTML.
e.g
var div = document.getElementsByTagName('div');
for (var i=0;i<div.length;i++){
console.log(div[i].innerHTML)
if(div [i].innerHTML == 'hello world'){
var element = div[i].parentElement
console.log(element)
break;
}
}
You could use outerHTML to search for it, however this only works if the element has a parent element.
var els = Array.from(document.querySelector('body *')); //this selects all elements in the body
var el;
for(var i = 0; i < els.length; i++) {
if(els.outerHTML === "<div id='myDiv'\>hello world</div\>") {
el = els[i];
}
}
//Use the el variable for your element

Change only the text of an anchor javascript

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.

Add Different Data Attribute to Anchors

I'm attempting to add data-webpart attributes to all the anchors within a document, but populate their values with the data attributes of their containing divs.
However the code I wrote appears to be populating all of the anchors with only one of the data attributes (or rather, adding the first one to all, then adding the second).
Any help would be much appreciated!
HTML
<body>
<div data-webpart="form">
Test Link
Test Link
Test Link
</div>
<div data-webpart="icon-grid">
Test Link
Test Link
Test Link
</div>
</body>
JavaScript
// data attributer
var webParts = document.querySelectorAll("[data-webpart]");
var webPartAnchors = document.querySelectorAll("[data-webpart] > a");
function addDataAttr() {
var closestWebPartAttr;
for (i = 0; i < webPartAnchors.length; i++) {
for (e = 0; e < webParts.length; e++) {
closestWebPartAttr = webParts[e].getAttribute("data-webpart");
webPartAnchors[i].setAttribute("data-web-part", closestWebPartAttr);
}
}
}
window.onload = function() {
if (webParts !== null) { addDataAttr(); }
};
Your nested loops are copying the data attribute from every DIV to every anchor, because there's nothing that relates each anchor to just their parent. At the end they all have the last data attribute.
Since the anchors are direct children of the DIV, you don't need to use querySelectorAll() to get them, you can just use .children() within the loop.
function addDataAttr() {
for (var i = 0; i < webParts.length; i++) {
var webpart = webParts[i].dataset.webpart;
var children = webParts[i].children;
for (var j = 0; j < children.length; j++) {
children[j].dataset.webpart = webpart;
}
}
}

How to remove all HTML tag by using the loop with Javascript

<div id='images'><img id='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
How to remove all <div> with the loop with Javascript?
Here is my code:
var value = document.getElementsByTagName("images");
for (var i = 0; i < value.length; i++) {
$(value[i]).remove();
}
You can only use same id value once per page. Change it to class, i.e. images
You will then have multiple div with class images and will be able to easily remove the spinners like this:
$(".images").remove();
If you have a lot of spinners, just wrap them with a div and remove the div. Something like this:
HTML:
<div id="jedi-wrapper">
<div class="images">
...
</div>
</div>
jQuery:
$("#jedi-wrapper").remove();
From the image, it looks like you are loading some values using AJAX. Why don't you remove the image on success?
Hope that helps
Seem like you want to remove all div with id images, but id is unique, you can use class instead:
<div class='images'><img class='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
then you can do:
$('.images').remove()
With your code you can do this:
document.getElementsByClassName("images").remove();
or more like jQuery:
$('.images').remove();
Althoug you can try this too:
var value = document.getElementsByClassName("images");
for (var i = 0; i < value.length; i++) {
$(value).eq(i).remove();
} //-------^^^^^^--------------you can make use of `.eq()` here
What your issue is there is no tag name like 'images' as your var suggests.
var value = document.getElementsByTagName("images");
images is the class name so you can use this:
document.getElementsByClassName("images")
Get element by ID, there's nothing with document.getElementsByTagName("images")
var c = document.getElementById('images');
var i, item = c.childNodes;
for (i = item.length; i--;) {
c.removeChild(item[i]);
}
You should probably be using class="images" instead of id="images" if that element is being rendered multiple times.
But to do this in a loop with raw javascript, you will need to first get the elements, convert them to an array, and then remove them in a loop.
var imageElements = doc.getElementsByClassName('images'),
images = Array.prototype.slice.call(imageElements);
for (var i = 0, l = images.length; i < l; i++) {
images[i].remove();
}
Notice that I don't just loop through imageElements... That's because getElementsBy...() returns a live list, so as soon as you remove() one of them, the list will be mutated and you will start running into undefined elements and javascript errors. To solve this, simply convert the live list to an array with Array.prototype.slice.call() and then loop through that array, removing the elements from the page.

How can I get an element's attribute from the parent's parent element's ID using JavaScript?

So I have the following HTML...
HTML:
<div id="col1">
<img src="1.jpg">
</div>
And I am implementing a HTML5 drag and drop feature where the inner html of col1 is changed for the dragged element's inner html - so basically the columns change their content.
I have another div (let's call that swap-text) where I want to change its text content depending on what image is presently inside col1.
This is why I want to figure out how I can obtain col1's img element's src attribute value through JavaScript so I can then write an if statement to change the content of the swap-text depending on which image is in col1.
I could add ID's to the img elements but then I still don't know how I would write the condition to check if say, img-id1 parent is col1.
Attempt(s):
var doc = document.getElementById("col1");
var children = null;
var imgEle;
//gets img node, but also got 1/2 text object(s)?
for (var i = 0; i < doc.childNodes.length; i++) {
children = doc.childNodes[i];
console.log(children);
}
//document.getElementById("img")
//children[1].getAttribute('src'); - cannot call method 'getAttribute' of undefined
//imgEle = doc.childNodes[0].getElementById('img'); - Object #<Text> has no method 'getElementById'
console.log(imgEle);
console.log(children);
This work fine pure javascript:
document.getElementById("col1").getElementsByTagName("img")[0].getAttribute("src");
var doc = document.getElementById("col1");
var img = document.getElementsByTagName('img')[0];
var imgParent = img.parentElement;
This is how you determine the elements parent/
I suggest you to use JQuery so you can simply use:
$("img").attr("id"); //Return the id of the img element
Check this:
var column = document.getElementById("col1");
var imgSrc = column.getElementsByTagName("img")[0].getAttribute("src");
Or just use the jQuery - it's simpler:
$('#col1 img').attr('src');
as you will only have one child node in col1 (the img), change the for loop.
var doc = document.getElementById("col1");
var children = null;
var imgEle;
//gets img node, but also got 1/2 text object(s)?
//for (var i = 0; i < doc.childNodes.length; i++) {
// children = doc.childNodes[i];
// console.log(children);
//}
childen = doc.childNodes[0];
// or children = doc.firstChild;
console.log(children);
//document.getElementById("img")
console.log(children.getAttribute('src')); - children is single object
//imgEle = doc.childNodes[0].getElementById('img'); - Object #<Text> has no method 'getElementById'
console.log(imgEle);
console.log(children);

Categories

Resources