Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sibling div id generated by PHP

I have HTML code for kind of blog page. Below - code of 1 post and its height cuts by CSS. It will be many posts on blog page. I want to see all content of particular page by clicking "Read More" button. Div with blog content has dynamic id which gets from database by PHP.

How can I change height of div with class "blog_article" by clicking "Read More" button?

I thought of using JS/Jquery but cannot get id of "blog_article" div. Or maybe there is some better way to do this?

<div class="blog_article_wrapper">  
  <div class="blog_article" id="<?php echo $id; ?>">    
    <!--Some content-->
   </div> 

    <div class="blog_article_read_more">
        <button onclick="blogReadMore()">Read More</button>
    </div>
 </div>
like image 418
Alexandr Avatar asked Feb 05 '16 19:02

Alexandr


2 Answers

but cannot get id of "blog_article" div

Why can't you?:

<button onclick="blogReadMore(<?php echo $id; ?>)">Read More</button>

Or, if it's a string:

<button onclick="blogReadMore('<?php echo $id; ?>')">Read More</button>

Then blogReadMore() has a reference to the id:

function blogReadMore(id) {
    // use the id to identify the element and modify it however you want
}

Conversely, since you tagged jQuery, you can traverse the DOM from the button click to determine the element without needing any id at all. Something like this:

$('.blog_article_read_more button').click(function () {
    var article = $(this).closest('.blog_article_wrapper').find('.blog_article');
    // do whatever you like with the article
});
like image 55
David Avatar answered Sep 29 '22 18:09

David


There's a more straight forward way than Azim's answer, but based on the same ideas:

I would still use the read_more class, although not actually needed. I will assume such a class applied to the button.

$('.read_more').click(function(){
    var blog_article = $(this).parent().parent().find('.blog_article');
    blog_article.css('height', '100px'); //change height here
});

In this case I use .parent() method in order to get the parent object from the clicked item, rather than relying on .closest(). Two calls to .parent() are needed because the <button> resides inside a <div> and we need the parent of that div before we can drill down.

Alternatively:

$('.read_more').click(function(){
    var blog_article = $(this).parent().prev();
    blog_article.css('height', '100px'); //change height here
});

Because the button's parent <div> is the direct sibling of the one we're interested in. No selectors needed at all!

like image 30
Draco18s no longer trusts SE Avatar answered Sep 29 '22 20:09

Draco18s no longer trusts SE