Get elements by class name in a certain div through Javascript - javascript

I have:
<div class="f0">
<div class="input-text">
<t>Text</t>
</div>
</div>
var h = 0;
for(h;h<inputstext.length;h++){
var str = 'f' + h;
var currentDiv = document.getElementById(str);
}
How do I get only the input-text elements value that is in f0?
Output should be Text.
Thanks.

You can use the element[property*="val"] to select all elements with property beginning with "val" - in this case, any class that starts with "f", and then select their .input-text children.
Also, you're trying to get elements with id f0, when these divs are marked with class f0.
const inputs = document.querySelectorAll('[class*="f"] .input-text');
for (const element of inputs)
console.log(element.textContent.trim());
<div class="f0">
<div class="input-text">
inside f0
</div>
</div>
<div class="f1">
<div class="input-text">
inside f1
</div>
</div>

Related

javascript replace node and all of it childs with anothe code

How can you replace HTML tag with all tags branching inside using Javascript with other HTML code?
example:
<div class="a">
<div class="sub-a1">
<div class="sub-a12">
</div>
</div>
<div class="sub-a2">
<div class="sub-b">
</div>
</div>
I wanna replace all tags from tag div class 'a' including all sub nodes with another code.
is that's possible?
please help me.
const target = document.querySelector(".a");
target.innerHTML = //place your html here as string
Yes, this is possible. If you want to keep the div.a elements and just change the "subnodes" you have to use innerHTML in stead of outerHTML.
const divs = [...document.getElementsByClassName("a")]; //make a copy of the HTML collection so that they can be removed without being removed in the array
const newElement = "<h1>Replaced Element</h1>"; //this is your replacement element
for (let i = 0; i < divs.length; i++) { // loop through all the divs
divs[i].outerHTML = newElement; // set the outer html for the div to the replacement elemzent
}
You can do with .replaceWith() with a valid HTML code.
function replace() {
var para = document.createElement("P"); // Create a <p> element
para.innerText = "This is a paragraph"; // Insert text
document.querySelector(".a").replaceWith(para);
}
<div class="a">
<div class="sub-a1">
<div class="sub-a12">
<h4>Sample content1</h4>
</div>
</div>
<div class="sub-a2">
<div class="sub-b">
<h4>Sample content2</h4>
</div>
</div>
</div>
<button onclick="replace();"/>Click to Replace</button>

jQuery ID Return is undefined although HTML ID is defined

I'm trying to retrieve the ID of one element, store it as a variable and then use that ID value to interact with other elements in that section with the same ID.
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">
</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore()">
</div>
</div>
And then the JS/jQuery
function readMore() {
var subID = event.target.id;
var newTarget = document.getElementById(subID).getElementsByClassName("articlePara");
alert(newTarget.id);
}
At this point I'm only trying to display the ID of the selected element but it is returning undefined and in most cases people seem to notice that jQuery is getting confused because of the differences between DOM variables and jQuery ones.
jsfiddle: https://jsfiddle.net/dr0f2nu3/
To be completely clear, I want to be able to click on one element, retrieve the ID and then select an element in the family of that clicked element using that ID value.
just remove the getElementsByClassName("articlePara"); in end of the newTarget .already you are call the element with id alert the element of the id is same with target.id
function readMore() {
var subID = event.target.id;
var newTarget = $('[id='+subID+'][class="articlePara"]')
console.log(newTarget.attr('id'));
console.log(newTarget.length);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainContent">
<div class="articleContent">
<h1>header</h1>
<p class="articlePara" id="one"></p>
</div>
<div class="articleFooter" id="one" onclick="readMore()">click
</div>
</div>
As you have read before, you should keep your id's unique, and you should avoid using onclick in html, but you could do it like this.
With querySelector you get the element and then with parentElement you can retrieve the parent of that element.
function readMore(el) {
var articleFooterId = el.id;
var articlePara = document.querySelector(".articleContent #"+articleFooterId);
var articleContent = articlePara.parentElement;
console.log('articleFooter', articleFooterId);
console.log('articlePara', articlePara);
console.log('articleContent', articleContent);
}
In your html you can return the 'this' object back to the function by doing readMore(this).
<div class="mainContent">
<div class="articleContent">
<h1>header1</h1>
<p class="articlePara" id="one">para1</p>
</div>
<div class="articleFooter" id="one" onclick="readMore(this)">footertext</div>
</div>
<div class="mainContent">
<div class="articleContent">
<h1>header2</h1>
<p class="articlePara" id="two">para2</p>
</div>
<div class="articleFooter" id="two" onclick="readMore(this)">footertext</div>
</div>
jsfiddle
if you're using Jquery:
$(function () {
$('div.articleFooter').click(function () {
var para = $(this).prev().find('p.articlePara').text();
alert('T:' + para);
});
})
$('.articleFooter').click(function() {
var b=subId; //can be any
var a="p[id="+b+"]"+"[class='articlePara']";
$(a).something;
});
You have forgotten to pass in event as parameter in your onclick= call in html.
In your javascript, you need to include event in the parenthesis as well.
window.readMore = function(event) {...}
if you write document.getElementById(subID).getElementsByClassName("articlePara"); That's saying you want to get your clicked element's CHILD elements that have class equal to articlePara . There is none. So you get undefined.
If you want to find all element with a ID one and a class articlePara, it can be done easily with jQuery:
newtarget = $("#one.articlePara");
You can insert a line: debugger; in your onclick handler function to trigger the browser's debugging tool and inspect the values of variables. Then you will know whether you are getting what you want.

Append element using jquery selector

I need to recreate and append my template div to the parent div on button click and this can be done multiple times
<div id = "parent">
<div id = "child_1">
<div><input type = "text"></div>
<div><input type = "text"></div>
//several inputs and divs
</div>
</div>
and my script
//on button click event
var template = $("#parent").children().last();
template.attr("id","child_2"); //just a sample of dynamic id
$("#parent").append(template);
But this doesn't work
You need to clone() a copy of the child before you append it, otherwise you just put the current element back in its original position.
var template = $("#parent").children().last().clone();
Working example
Try with this:
var html = $("#parent").html();
var i = 1;
$("button").on("click",function(){
i++;
$("#parent").append(html.replace('id="child_1"','id="child_' + i + '"'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id = "parent">
<div id = "child_1">
<div><input type = "text"></div>
<div><input type = "text"></div>
//several inputs and divs
</div>
</div>
<button>Click</button>

Why can i not add an ID to an element using pure javasctipt? setattribute is not a function

I'm trying to add an ID to one particular element which all have the same class name this is an example but it won't work on the example here is what i am trying.
<div class = "ABC">
<p> child </p>
</div>
<div class = "ABC">
<p> child </p>
</div>
<div class = "ABC">
<p> child </p>
</div>
<div class = "ABC">
<p> child </p>
</div>
var ref = document.getElementsByClassName("ABC")[3];
var ref2child = ref.childNodes
var addID = ref2child.setAttribute("id", "HOV")
when i look in the console it says Uncaught TypeError: ref2child.setAttribute is not a function(…)
The ref.childNodes give you a list of nodes, so you need to tell which by adding an index, like this ref.childNodes[0].
As ref.childNodes also return text nodes, a better method would likely be ref.children
Note: The setAttribute method doesn't have a return value
Note 2: When you run it on your code, make sure the script executes either at the end of the body or in the onload/domready event, or else you will get that error as the element is not yet available.
var ref = document.getElementsByClassName("ABC")[3];
var ref2child = ref.children[0];
ref2child.setAttribute("id", "HOV");
/* this line is only for demo purpose, showing this method works */
ref2child.innerHTML += ref2child.getAttribute("id");
<div class = "ABC">
<p> child </p>
</div>
<div class = "ABC">
<p> child </p>
</div>
<div class = "ABC">
<p> child </p>
</div>
<div class = "ABC">
<p> child </p>
</div>
Yes setAttribute is not function for the collection of child nodes.
Try this :
var refs = document.getElementsByClassName("ABC");
var ref2child = refs[0];
ref2child.setAttribute("id", "HOV")
// Now this should give you a reference to the item
var itemWithId = document.getElementById('Hov')

How to get the closest previous element in jQuery?

I want to get the closest object tag from the currently selected object tag. But it has to be strictly above. Suppose I have the object with id A. How can I get the closest object tag above it? In this case I want to get the object tag with id B. Each div container can contain a object tag or something else.
<div class="message">
<span></span>
</div>
<div class="message">
<object id="C"></object>
</div>
<div class="message">
<object id="B"></object>
</div>
<div class="message">
<span></span>
</div>
<div class="message">
<object id="A"></object>
</div>
<div class="message">
<object id="Z"></object>
</div>
Assuming this is the object with ID A
$(this).closest('.message').prevUntil('.message:has(object)').prev().find('object');
FIDDLE
traverses up to the closest .message then checks previous elements until it finds one that contains an object tag, then it stops, but it stops at the element before that tag, so we call prev to go one step further, and then use find to find the object tag.
Another option:
var objs=$('object').toArray();
$('.message').on('click',function(){
var elem=$(this).children().get(0);
if(objs.indexOf(elem)-1>=0){
console.log(objs[objs.indexOf(elem)-1]);
console.log(objs[objs.indexOf(elem)-1].id);
}
});
You can use prev() to get the previous sibling element. That will get you partway there, but since each 'message' div is not guaranteed to contain an object element you'll need to use prevUntil() or run your own iteration/search.
For instance:
var lastObj = $("#A");
var parent = lastObj.parent();
var previousObject = parent.prevUntil(".message:has(object)").prev().find("object");
Or without prevUntil():
var lastObj = $("#A");
var parent = lastObj.parent();
var previousObject = undefined;
while (parent.length > 0 && ! previousObject) {
parent = parent.prev();
if (parent.find("object").length > 0) {
previousObject = parent.find("object");
}
}
Or as a runnable code snippet (using classes instead of object tags):
$(".object").click(function(){
var myId = this.id;
var prevId = undefined;
var parent = $(this).parent();
var previousObject = undefined;
while (parent.length > 0 && ! previousObject) {
parent = parent.prev();
if (parent.find(".object").length > 0) {
previousObject = parent.find(".object");
prevId = previousObject.attr("id");
}
}
alert("clicked=" + myId + ", previous=" + prevId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message">
<span></span>
</div>
<div class="message">
<span class="object" id="C">C</object>
</div>
<div class="message">
<span class="object" id="B">B</object>
</div>
<div class="message">
<span></span>
</div>
<div class="message">
<span class="object" id="A">A</object>
</div>
<div class="message">
<span class="object" id="Z">Z</object>
</div>

Categories