i want to target the element above my show more button, so when i click the button more text appears i don't want to target it by class name or id
here is my code
<div class="ccontainer" id="ccontainer">
<p id="context"> content </p>
<div class="img" id="cntimgcon" >
<img src="images\image2.jpg" id="cntimgp1">
</div>
<p id="context"> content </p>
</div>
<Button id="showmore" onclick=" this.parentElement.style.maxHeight = 'none'"> show more </button>
Don't refer to the IDs that can get cumbersome. Instead give your show more button a class to refer to. That will give you the ability to add many to the same page without needing to adjust/track the IDs.
This is a basic example that toggles a class on the content div that will show the full div. Obviously the details are up to your specific needs.
Using previousElementSibling allows you to refer to the previous element.
document.addEventListener("click",function(e){
let btn = e.target;
if(btn.className.indexOf("showmore") > -1){
btn.previousElementSibling.classList.toggle("active");
}
});
.ccontainer{
height:50px;
overflow:hidden;
border:1px solid #000;
margin:10px 0;
padding:10px;
}
.ccontainer.active{
height:auto;
}
<div class="ccontainer">
<p id="context"> content </p>
<div class="img" id="cntimgcon" >
<img src="images\image2.jpg" id="cntimgp1">
</div>
<p id="context"> content </p>
</div>
<Button class="showmore"> show more </button>
<div class="ccontainer">
<p id="context"> content3 </p>
<div class="img" id="cntimgcon" >
<img src="images\image2.jpg" id="cntimgp1">
</div>
<p id="context"> content4 </p>
</div>
<Button class="showmore"> show more </button>
When using jQuery you can use:
$(this).prev(); // $(this) is equal to the button
// or very specific
$(this).prev(".container");
Using vanilla JS you could use something like
onclick="this.previousSibling"
not sure if vanilla js has a way of selecting a previous node by identifier.
Any whitespace or comment block is also considered a previousSibling, so be careful with that.
html
<div>
<div class="ccontainer" id="ccontainer">
<p id="context"> content </p>
<div class="img" id="cntimgcon" >
<img src="images\image2.jpg" id="cntimgp1">
</div>
<p id="context"> content </p>
</div>
<Button id="showmore" onclick="hideParent(this)"> show more </button>
</div>
js
function hideParent(elm){
console.log(elm.previousElementSibling.innerHTML )
}
see https://jsfiddle.net/rkqnmv0w/
If your using only vanila JS you can access the previous element with the previousElementSibling property.
Example:
var showMoreButton = document.getElementById('showmore');
var previousElement = showMoreButton.previousElementSibling;
Related
I have a few buttons in the HTML file code with Bulma similar like this:
<a class="button" data-target="A">Section A</a>
<a class="button" data-target="B">Section B</a>
<a class="button" data-target="C">Section C</a>
And there are a few section like this which can interact with the buttons:
<div id="A" class="contentswitch">
<article class="message">
<div class="message-header" id="h1">
<p>Section A-1</p>
</div>
<div class="message-body">
Message 1 of section A
</div>
<div class="message-header">
<p>Section A-2</p>
</div>
<div class="message-body">
Message 2 of section A
</div>
</article>
</div>
As I add code like this in the JS, it can add a class called "is-hidden" to all the div ejectment which contains "contentswitch" class.
$("a.button").on("click", function(){
$("div.contentswitch").addClass("is-hidden");
});
What can I do if I want to remove the class ("is-hidden") from specific div element, like if I click the button of Section A, then it add "is-hidden" class to all the div element contain content switch then remove it from the div element with the id "A"?
Thank you so much
You can use data-target to connect the clicked button to the div you want to show. And hide the rest of them.
Also, use button iso a tag. a tag has a specific purpose in HTML and should be used only in combination with href attribute.
const buttons = $('.button');
const contentSwitchDivs = $('.contentswitch');
buttons.on("click", function(){
const btnTarget = $(this).data('target')
const contentToShow = $(`#${btnTarget}`)
contentSwitchDivs.not(btnTarget).hide();
contentToShow.show();
});
.contentswitch {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="button" data-target="A">Section A</button>
<button class="button" data-target="B">Section B</button>
<button class="button" data-target="C">Section C</button>
<div id="A" class="contentswitch">
A contentswitch
</div>
<div id="B" class="contentswitch">
B contentswitch
</div>
<div id="C" class="contentswitch">
C contentswitch
</div>
I have this HTML:
<p></p>
<div class="comment_like">
<span class="reaction_2 tooltipstered" id="like13seperator2" rel="unlike"><i
class="likeIconDefault"></i>Like</span>
</div>
Now I want to add this div: <div class="commentLikeCount"></div> before this comment_like class using jQuery.
I am trying with this code:
$("#like"+posts_id).parents(".comment_like").prepend('<div class="commentLikeCount"></div>');
but somehow not working :(
Updated for the new Questions:
Now I have that HTML:
<p></p>
<div class="commentLikeCount">
<br>
<span class="float-right"> 1</span>
<img src="assets/images/db_haha.png" alt="" class="float-right old">
<img src="assets/images/db_love.png" alt="" class="float-right">
</div>
<div class="comment_like">
<span class="unLike_2" id="like13seperator2" rel="unlike">
<i class="loveIconSmall likeTypeSmall"></i>Love
</span>
</div>
Now, I just want to remove the last Img from the coomentLikeCount class.
You can use insertBefore:
$('<div class="commentLikeCount" />')
.insertBefore($("#like"+posts_id).parents(".comment_like"))
Or before:
$("#like"+posts_id).parents(".comment_like")
.before('<div class="commentLikeCount" />')
If you're inserting commentLikeCount in every .comment_like, then just use $('.comment_like') instead of $("#like"+posts_id).parents(".comment_like")
Regarding your comment:
well if I already have this div then how can select this div?
You can prepend using insertBefore like:
$('.commentLikeComment').insertBefore($("#like"+posts_id).parents(".comment_like"));
To your updated question, you can remove last image like:
$('.commentLikeCount img').last().remove()
You can do with before().
$(".comment_like").before("<div class='commentLikeCount'></div>");
I'm completely new to JavaScript and struggling to get this working. I'm trying to display contact details in an alert box when a button is clicked.
The information is displayed in nested DIVs outlined below:
<div class="info-and-actions">
<div class="info">
<div class="name-container">
<h4 class="name">Trader 1</h4>
</div>
<div class="details-container">
<p class="tele">###############</p>
<p class="email">hello#url.com</p>
</div>
<div class="actions">
<button class="displayContactDetails">Display contact details</button>
</div>
</div>
</div>
<div class="info-and-actions">
<div class="info">
<div class="name-container">
<h4 class="name">Trader 2</h4>
</div>
<div class="details-container">
<p class="tele">###############</p>
<p class="email">hello#url.com</p>
</div>
<div class="actions">
<button class="displayContactDetails">Display contact details</button>
</div>
I am using this JavaScript with an event listener on the displayContactDetails button to display the contact details in the alert box.
function displayContactDetails() {
var contactName = document.querySelector("a.name-link.profile-link").textContent;
var contactTele = document.querySelector("p.tele").textContent;
alert("Contact " + contactName + " on " + contactTele);
}
This currently displays the first trader's contact details when any displayContactDetails button is clicked.
What I want to do is select the relevant contact information from the parent elements of the button (.name-container and .details-container) - so when the second button is clicked, Trader 2's details are displayed.
How do I traverse the DOM to achieve this?
Your event will have the necessary info to locate the corresponding telephone element.
function displayContactDetails(e) {
var contactName = e. currentTarget // this is the element that has the click listener
.parentNode // this would be .actions div
.parentNode // this would be .info div
.querySelector('.name a') // the link with the name
.innerHTML; // the inner contents of the link, in this case the name
// repeat but change querySelector to grab the telephone
alert("Contact " + contactName + " on " + contactTele);
}
or easier with jquery
$('.displayContactDetails').on('click', function(e){
var name = $(this)
.closest('.info') // goes up in the tree until .info
.find('.name').html(); // then back to .name and get content
alert(name);
});
With jquery it is not only easier, but it is also more resilient to changes in the html structure. Jquery will go up the DOM tree until it finds the .info div. With plain js you have to hardcode the number of times to jump to the parent element, or make a loop for it.
You can also try the other answers suggested but you also have to maintain the additional id's and markup required for it to work.
i hope passing a unique info on the function call
function displayContactDetails(id){
var contactName = document.getElementById("name-link-"+id).textContent;
alert("Contact " + contactName );
}
<div class="info-and-actions">
<div class="info">
<div class="name-container">
<h4 class="name">Trader 1</h4>
</div>
<div class="details-container">
<p class="tele">###############</p>
<p class="email">hello#url.com</p>
</div>
<div class="actions">
<button class="displayContactDetails" onclick="displayContactDetails('one')">Display contact details</button>
</div>
</div>
</div>
<div class="info-and-actions">
<div class="info">
<div class="name-container">
<h4 class="name">Trader 2</h4>
</div>
<div class="details-container">
<p class="tele">###############</p>
<p class="email">hello#url.com</p>
</div>
<div class="actions">
<button class="displayContactDetails" onclick="displayContactDetails('two')">Display contact details</button>
</div>
I want to put a div in another div using js. I found a solution can do this but just put 1 div in div. Below html is my situation.
For example:
<body>
<div>
<span class="outer_part">
</span>
<div class="inner_part">1
</div>
</div>
<div>
<span class="outer_part">
</span>
<div class="inner_part">2
</div>
</div>
<div>
<span class="outer_part">
</span>
<div class="inner_part">3
</div>
</div>
</body>
Result:
<body>
<div>
<span class="outer_part">
<div class="inner_part">1</div>
</span>
</div>
<div>
<span class="outer_part">
<div class="inner_part">2</div>
</span>
</div>
<div>
<span class="outer_part">
<div class="inner_part">3</div>
</span>
</div>
</body>
I found solution but not work
<script>
$('.inner_part').appendTo('span.outer_part');
</script>
Your problem is that you appending all the .inner_part elements to all the .outer_part elements, but you only need to do a portion of that.
You can use each() to loop over all the .inner_parts, and attach each to its previous sibling, which is the .outer_part.
// loop over all inner parts
$('.inner_part').each(function() {
var innerPart = $(this);
var outerPart = innerPart.prev(); // inner part's previous sibling is the outer part
innerPart.appendTo(outerPart);
});
Or, shorter:
$('.inner_part').each(function() {
$(this).appendTo($(this).prev());
});
Get element by the ID, then add html inside of it to add a div in this case or anything you want.
document.getElementById('div1').innerHTML += '<div class="inner_part">1</div>';
<div id="div1"></div>
I am building a Chrome extension (and therefore can only use JavaScript) and I need to get the link that resides in the h2 with the heading2 class.
However, there are multiple h2 items with that class (not shown here), and I will not know what the link will point to, as it changes monthly.
In this example, the content of the header is "Think before you tweet". It will always be under another header that contains the words "Featured Topic."
What I am looking to get is the /think_before_you_tweet from the href= of that h2 item. It shows that I have already completed the topic underneath the h2, but that will not always be the case.
Here is the code for the website:
<div class="chosen_for_you_section">
<div class="internal_container">
<h2 class="section_header"><img src="/public/s360/img/360-spinner.png" class="s360LogoHeader">Featured Topic <i class="fa fa-info-circle"></i> <span class="infoTxt">Read about what to do</span></h2>
<article class="article_block masonry_item " data-article_id="431">
<div class="article_image">
<img src="/thumb/public/media/nh/images/twitter_tweet_think_before_send.png?q=&h=278" />
<i class="fa fa-check-square-o article_complete article_type_icon" title="Article"></i>
<div class="action_icons">
<span class="like "><a title="Favorite"><i class="fa fa-heart"></i></a></span>
</div>
</div>
<header>
<h2 class="heading2">Think Before You Tweet!</h2>
<div class="article_required_complete">Congratulations, you've completed this required topic.</div>
<div class="category_blocks">
<p>
Social Media
</p>
</div>
</header>
</article>
<div class="focus_items">
<div class="home_side">
<p>
<img alt="" src="" style="width: 430px; height: 422px;" /><!-- I hid the img src here because it reveals some personal information and is not important -->
</p>
<p></p>
</div>
</div>
</div>
</div>
I can use jQuery in my extension, but I do not have any back-end capabilities.
Use jQuery :contains selector:
$('h2.section_header:contains("Featured Topic") + article a')[0].href
Looks like you've gotta loop through the h2.section_header headers, see if the text matches whatever you want, and then grabs the link from the header following itself.
$('h2.section_header').each(function(index, element) {
var $element = $(element);
if ($element.text().match(/Featured Topic/i)) {
$('#result').html($element.next('article').find('h2.heading2 a').attr('href'));
}
});
#result {
border: 3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
<div class="chosen_for_you_section">
<div class="internal_container">
<h2 class="section_header"><img src="/public/s360/img/360-spinner.png" class="s360LogoHeader">Featured Topic <i class="fa fa-info-circle"></i> <span class="infoTxt">Read about what to do</span></h2>
<article class="article_block masonry_item " data-article_id="431">
<div class="article_image">
<img src="/thumb/public/media/nh/images/twitter_tweet_think_before_send.png?q=&h=278" />
<i class="fa fa-check-square-o article_complete article_type_icon" title="Article"></i>
<div class="action_icons">
<span class="like "><a title="Favorite"><i class="fa fa-heart"></i></a></span>
</div>
</div>
<header>
<h2 class="heading2">Think Before You Tweet!</h2>
<div class="article_required_complete">Congratulations, you've completed this required topic.</div>
<div class="category_blocks">
<p>
Social Media
</p>
</div>
</header>
</article>
<div class="focus_items">
<div class="home_side">
<p>
<img alt="" src="" style="width: 430px; height: 422px;" /><!-- I hid the img src here because it reveals some personal information and is not important -->
</p>
<p></p>
</div>
</div>
</div>
</div>
with jQuery's :contains selector use this:
jQuery('h2:contains("Featured Topic") ~ article h2.heading2 a').attr('href')
try at http://jsfiddle.net/ug01a0d2/
without jQuery try to bind to class "section_header" or use a cycle with the textContent check to iterate all "h2.section_header"
If there are multiple H2 class heading2 :
$('h2[class*="heading2"] a').each(function(){
var href = $(this).attr('href');
// Do what you want with this href
});
Use XPath! The syntax is pretty, uh, unfortunate, but it's very powerful:
var result = document.evaluate('//h2[#class="section_header"]/following-sibling::article//h2[#class="heading2"]/a', document, null, XPathResult.ANY_TYPE, null );
That should select that anchor node. I'm not sure if it's available to extensions, but Chrome defines a handy helper method called $x that eliminates all that boilerplate around the query.
More information: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript