Get innerHTML for a parent parent in JavaScript - javascript

I have this code:
<div class="places-item">
<div class="places-item-img"></div>
<div class="places-item-header">
<h2>TEST</h2>
<div class="places-item-header-add">ADD</div>
</div>
</div>
document.querySelector('.places-item-header-add').addEventListener('click',function(){
var getHTML = this.outerHTML;
document.querySelector('body').innerHTML = getHTML
});
The current code only displays div.places-item-header-add, and I want the entire div.places-item to be displayed. Is that possible?

I think this is what you are asking for:
document.querySelector('.places-item-header-add').addEventListener('click',function(){
document.querySelector('body').innerHTML = this.parentElement.parentElement.outerHTML;
});

Related

How to get previous element from click target?

Hello I have this html code:
<div class="row newrow">
<div class="col-10"><b>this</b></div>
<div class="col-2">
<img src="close.png" id="exit"/>
</div>
</div>
When I click on img with id exit using this code
$('body').on('click','#exit',function(e){
})
I need to get the text of the <b>behind it which would be "this"
I have tried this but it does not work:
$('body').on('click','#exit',function(e){
$q = $(e.target).prev('b')
var word = $q.text()
)}
It only gives me the that I clicked from the beginning
try this:
$('body').on('click','#exit',function(e){
var this_b = $(this).parent().prev().children(0).html();// get the text
alert(this_b);
});
You can use $(this).closest('.row').find('b'):
$('#exit').click(function(e){
$q = $(this).closest('.row').find('b');
var word = $q.text();
console.log(word);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row newrow">
<div class="col-10"><b>this</b></div>
<div class="col-2">
<img src="close.png" id="exit"/>
</div>
</div>
You need to select the parent of the clicked img to get the the .col-2, and then get the col-2's prev() to get to the .col-10, and then you can access its children() to get the children (the single <b>). Also, there's no need for e.target if you use this:
$('body').on('click', '#exit', function() {
$q = $(this).parent().prev().children();
var word = $q.text()
console.log(word);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row newrow">
<div class="col-10"><b>this</b></div>
<div class="col-2">
<img src="close.png" id="exit" />
</div>
</div>
Try this
$('body').on('click','#exit',function(e){
var word = $(this).closest('.newrow').find('b').text();
});

Applying links via JavaScript

Hullo, I am wondering how I can add a new link around/to an element, using only JavaScript? I am new to JavaScript, and I am sorry if this question seems stupid or too easy.
Current:
<div class="container">
<div class="content1"></div>
<div class="content2"></div>
</div>
Desired Code:
<div class="container">
<div class="content1"></div>
<a href="http://example.com">
<div class="content2"></div>
</a>
</div>
Just use normal DOM manipulation, nothing tricky required
const container = document.querySelector('.container');
const a = container.appendChild(document.createElement('a'));
a.href = "http://example.com";
a.appendChild(document.querySelector('.content2'));
console.log(container.innerHTML);
<div class="container">
<div class="content1"></div>
<div class="content2"></div>
</div>
Can use jQuery wrap()
$('.content2').wrap('<a href="http://example.com">')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="content1">content 1</div>
<div class="content2">content 2</div>
</div>
Create a new a element and create a child in that element with the same content in your div and append the a element in the parent of the old div('.container')
var content2 = document.getElementsByClassName('content2')[0];
var container = content2.parentNode;
var a = document.createElement('a');
a.setAttribute("href", "www.google.com");
container.replaceChild(a, content2);
a.appendChild(content2);
<div class="container">
<div class="content1">Content1</div>
<div class="content2">Content2</div>
</div>
Using only pure Javascript, you can do something like this:
1. get your div by class (you can do using getElementById if you define an id for your div)
var mydiv = document.getElementsByClassName('content1');
2. create your anchor and set an href
var new_anchor = document.createElement("a");
new_anchor.href = "http://example.com";
3. Place the div content1 inside new anchor
new_anchor.append(mydiv[0]);
4. Place your entire element inside the container again
var mycontainer = document.getElementsByClassName('container');
mycontainer[0].insertBefore(new_anchor, mycontainer[0].childNodes[0])

jquery clone a link (once per div)

I have a set of divs, and need to clone the link from the top and insert into the last div (mobile-link). It is either cloning the links from all of the divs, and then inserting all of them at once, or if I use :eq(0), it's putting the first link into all of the divs.
<div class="course">Accounting</div>
<div class="start-date">1-1-2017</div>
<div class="credits">4</div>
<div class="location">Online</div>
<div class="mobile-link"></div>
<div class="course">Business</div>
<div class="start-date">1-1-2017</div>
<div class="credits">3</div>
<div class="location">Online/Campus</div>
<div class="mobile-link"></div>
<script>
$(".course a:eq(0)").clone().appendTo(".mobile-link");
</script>
What do I need to change to make this work properly?
You need to process each anchor separately:
$(".course").each(function() {
var myLink = $(this).find('a').clone();
$(this).nextAll('.mobile-link').first().append(myLink);
});
Demo fiddle
Append method can take a function as argument, and here it is appending to the each .mobile-link first <a> from his previous .course div
$(".mobile-link").append(function(){
return $(this).prevAll('.course:first').find('a:first').clone();
});
Check the below snippet
$(".mobile-link").append(function(i) {
return $(this).prevAll('.course:first').find('a:first').clone();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="course">Accounting
</div>
<div class="start-date">1-1-2017</div>
<div class="credits">4</div>
<div class="location">Online</div>
<div class="mobile-link"></div>
<div class="course">Business
</div>
<div class="start-date">1-1-2017</div>
<div class="credits">3</div>
<div class="location">Online/Campus</div>
<div class="mobile-link"></div>
I beleive that you should use last (If I understood question correctly):
var lastDiv = $(".mobile-link").last();
$(".course a:eq(0)").clone().appendTo(lastDiv);
Here is jsfiddle: fiddle

How can I Target parent and child class I javascript

<div id="inst4" class="block_navigation block">
<div class="content">
<div> Content Start here !!!</div>
</div>
</div>
<script>
var blockNav = document.getElementsByClassName("block_navigation")[0].getElementsByClassName("content");
blockNavIcon = document.createElement("img");
blockNavIcon.setAttribute("src", blockIcon);
blockNav.appendChild(blockNavIcon);
}
</script>
Here I am targeting content class, but it is not working, How can i do this any solution.
There are few problems in your script, you are using the class block_navigation twice, also blockNav is a NodeList
You can easily use .querySelector()
var blockNav = document.querySelector(".block_navigation .content");
blockNavIcon = document.createElement("img");
blockNavIcon.setAttribute("src", '//placehold.it/64');
blockNav.appendChild(blockNavIcon);
<div id="inst4" class="block_navigation block">
<div class="content">
<div>Content Start here !!!</div>
</div>
</div>
You can use use .getElementsByClassName("content")[0]
Hope this wil be helpful
var blockIcon = "http://weknowyourdreams.com/images/forest/forest-04.jpg";
var blockNav = document.getElementsByClassName("block_navigation")[0]
.getElementsByClassName("content")[0]; // Will select the child element
blockNavIcon = document.createElement("img");
blockNavIcon.setAttribute("src", blockIcon);
blockNav.appendChild(blockNavIcon)
JSFIDDLE

$().next() returning the same element multiple times

I tried to name the title as best I could. A little difficult for me to explain.
I'm having an issue with some code I'm writing (which runs in a widget on my wordpress site.) What I've written here emulates this issue. Just fyi I'm very new to jquery, JS, etc.
What I'm trying to do is set the variable "thumb" to the element after "widget-code". It works, however it's only finding that element ("thumb-class") in "wordpress-post1"
The console output is:
wordpress-post1
wordpress-post1
wordpress-post1
But it should be:
wordpress-post1
wordpress-post2
wordpress-post3
This is the actual code
<div class="wordpress-post1">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("#widget-code").next();
console.log(thumb[0].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post2">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("#widget-code").next();
console.log(thumb[0].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post3">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("#widget-code").next();
console.log(thumb[0].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
I'm going to try and clarify a little more:
This code is placed in an html widget which the wordpress theme I'm using provides. It hooks into each post. This is the only place I can put code, and this is the only code I've written. (I haven't altered the theme's files in any way.)
I have no control over the name of the classes or IDs. And they're dynamic. An unlimited number of posts could exist. Therefore I can't hardcode anything.
In order for this code to work correctly it'll need to find the sibling of the "widget-code" element in only the post it's running from.
This is the link to the code on JSFiddle: http://jsfiddle.net/pattnvy3/
Would appreciate any help on the matter.
If you want a nasty hack, try
<div class="wordpress-post1">
<div id="widget-code">
<script>
$(document).ready(function(){
var c = window['widget-code-counter'] || 0;
window['widget-code-counter'] = ++c;
var className = 'wordpress-post' + c;
console.log(className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
Demo: Fiddle
It will give the container class wordpress-post1, then you can use it to find any of the descendant element.
As per the immediate comments, it is invalid markup to use an id for multiple elements. That said, changing your id to a class such that:
<div class="wordpress-post[some-number-here]">
<div class="widget-code">
</div>
<div class="thumb-class">
</div>
</div>
would allow you to to a jQuery selector like so:
$('.widget-code').each(function (){
var thumb = $(this).next();
console.log(thumb[0].parentElement.className);
});
However, if I may make a recommendation, I would say that you tag each of your wordpress-post divs with the class "wordpress-post" and then have a more specific id which is the value you want to print.
Then it would look like this:
<div id="wordpress-post[some-number-here]" class="wordpress-post">
<div class="widget-code">
</div>
<div class="thumb-class">
</div>
</div>
and your javascript like this (with jQuery):
$('.widget-code').each(function (){
var post = $(this).closest('.wordpress-post');
console.log(post.attr('id'));
});
or even simpler:
$('.wordpress-post').each(function (){
console.log($(this).attr('id'));
});
depending on the needs you have. If you have any questions as to what you need, feel free to comment and I will get back to you as soon as I can.
A pure javascript method:
This is just a workaround since you have no control over ids or classes, this will target all div elements on the page, loop through them and search for any that contains wordpress-post in the class name.
window.onload=function(){
var posts=document.getElementsByTagName('div');
for(var i=0; i<posts.length; i++){
if(posts[i].className.indexOf("wordpress-post")> -1){
console.log(posts[i].className);
//Snippet Use
alert(posts[i].className);
}
}}
<div class="wordpress-post1">
<div id="widget-code"></div>
<div class="thumb-class"></div>
</div>
<div class="wordpress-post2">
<div id="widget-code"></div>
<div class="thumb-class"></div>
</div>
<div class="wordpress-post3">
<div id="widget-code"></div>
<div class="thumb-class"></div>
</div>
If you have any questions, please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
This can help if you want to have multiple IDs:
$(document).ready(function(){
$("[id^=widget-code]").each(function(){
console.log(this.parentElement.className);
});
});
But, still multiple same Ids are not recommended.
FIDDLE
Update: Declare a global variable var i=0; and keep increment it like :
<div class="wordpress-post1">
<div id="widget-code">
<script>
var i=0;
$(document).ready(function(){
var thumb = $("[id^=widget-code]").next();
console.log(thumb[i++].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post2">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("[id^=widget-code]").next();
console.log(thumb[i++].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
<div class="wordpress-post3">
<div id="widget-code">
<script>
$(document).ready(function(){
var thumb = $("[id^=widget-code]").next();
console.log(thumb[i++].parentElement.className);
});
</script>
</div>
<div class="thumb-class">
</div>
</div>
DEMO

Categories

Resources