Refer to attributes from multiple selector in jQuery - javascript

I have a bunch of DIVs identified by class screen-cat-comment and I want for each div to execute a plugin that receives as a parameter an attribute value from each DIV.
<div class="screen-cat-comment" catId="1"></div>
<div class="screen-cat-comment" catId="2"></div>
<div class="screen-cat-comment" catId="3"></div>
then, the selector
$('.screen-cat-comment').fragment({ code: $(this).attr('catId') });
Passing catId to myPlugin doesn't work -- from the current code, $(this).attr('catId') returns undefined. Is there any way to re-write this selector to pass attr('catId') to the plugin?

this in that context is probably the window...
$('.screen-cat-comment').each(function(){
$(this).fragment({ code: $(this).attr('catId') });
});

Related

jQuery cannot find class element from some html returned via ajax call

I am running an ajax call that returns some HTML as a string. For the purpose of this question I will call this <div class='abc'>ABC123</div> when I get this back I want to check and see if the class "abc" has a value and what that value is. However when I run a .find() I cannot find the class, I can find the div, but not the specific class. Just using the div is not adequate because in the real live code the HTML is very complex and has many divs and classes. Below is some JS that illustrates my point.
var x = "<div class='abc'></div>";
$(x).hasClass("abc"); // returns true
$(x).find(".abc"); // Returns empty array
Why is it that the first line returns true, but the selector cannot find the element?
Thanks!
Because $x is the div with class abc.
jquery .find() tries to find any children within the div.abc with class abc which it won't find.
This is more like it.
var x = "<div class='abc'><div class='def'></div></div>";
$(x).hasClass("abc"); // returns true
$(x).find(".def"); // returns $('div.def')
When we append html element to the page, sometimes JQuery can't find this element due to parent and child relationship.
For example: a button having class submit inside a div having id append_area and we want to run a function on click on this button. Then we can use the below code.
HTML Code:
<div id="append_area">
</div>
Jquery Code:
$("#results").delegate('.submit', 'click', function(){ });

Recieving two values from data attribute one being undefined

I am trying to link to divs together by linking the data-attribute name with the id but seem to receive an error
<div class="pod-container grid_3" data-name="#george">
<div class="pod">
<img src="img/example1.png" alt="">
</div>
</div>
<div id="george">Hello World</div>
I'm referencing jQuery 1.8.3 and using the following code to identify the data attribute on the div i click
<script>
$('.pod-container').click(function(){
var identifyId = $(this).data('name');
console.log(identifyId);
//$(identifyId).show();
});
</script>
but when it is logged in the console I get.
#george testdoc.html:123
undefined testdoc.html:123
You've got two elements with class "pod". One of them has a data-name attribute, and one doesn't. Each click will trigger the event handler on both elements.
Just grab the elements that have the data-name. What you're currently doing is targeting just .pods which may or may not have data-name. With the below code, you're just being specific.
$('.pod[data-name]').click(function(){
var identifyId = $(this).data('name');
console.log(identifyId);
//$(identifyId).show();
});
You have 2 elements with the pod class and are getting 2 events fire. The inner div does not have a data-name attribute.

How to get element by both id and class

Is there any alternative solution (in JavaScript) for document.getElementById(); to select a specific element, specifying both the class and id ?
for example I have such a content:
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="2"></div>
And I want to select the corresponding div under the "Question X" link in the function
function showQuestion(id)
{
var thediv = GetByClassAndId("q_content",id); // how to implement this function ?
WriteQuestionIn(thediv); //Ajax
}
Thanks in advance.
you can try document.querySelector()
like document.querySelector(".q_content#2") use the para like css selector..
Since ID is always unique (unless u make a mistake) u have no need to use both class and id to select the element.
Such an approach is not correct, and should be avoided at all cost.
What I suspect is your problem, is that the ID is only a number. Try adding a prefix which is a letter. Do view source to this page to see examples.
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="q1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="q2"></div>
function showQuestion(id)
{
var thediv = document.getElementById("q"+id);
WriteQuestionIn(thediv); //Ajax
}
Actually there is a function $ in jQuery for doing this operation. If you are using any framework, then you should remember there is always a jQuery library available. Else if you are using custom PHP, then add one of them like jQuery or other because they provide lots of types of selectors.
Now here is the code after adding jQuery:
$("#yourid") //basic selector
$("#yourid.yourclass").show()
Use .show() to show the selected element
Use .hide() To hide element

I need to pass two elements to an onclick event handling function JavaScript and not just their id's

Suppose I have two elements in my code and I want to pass their respective id's to an event handling function. (In my example below, I have a div and a button)
<div id="div1">
<input type="button" id="button1" onclick="doSomething(this, [here comes id of div])" />
</div>
For the button, instead of writing the id which is "button1", I simply passed the element itself using the this keyword. Now my question is, is there a way where I can pass the div element itself in the function and not just its id just like what I did with the button element?
Any help would be greatly appreciated.
You can use the parentNode property;
this.parentNode
As this returns a DOMElement (similar to this), you can access the ID the same via;
this.parentNode.id
... should you want to.
Just get it from the parent in the callback:
function clickHandler(e){
console.log(e.target.parentNode.id);
}
Why do you need to pass it in the first place? Access the div via parentNode.
onclick="doSomething(this);"
and
function doSomething(btn) {
var div = btn.parentNode;
}

How to clear all <div>s’ contents inside a parent <div>?

I have a div <div id="masterdiv"> which has several child <div>s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>s inside the master <div> using jQuery?
jQuery's empty() function does just that:
$('#masterdiv').empty();
clears the master div.
$('#masterdiv div').empty();
clears all the child divs, but leaves the master intact.
jQuery('#masterdiv div').html('');
Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.
$('#masterdiv div').empty();
Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.
I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
The better way is :
$( ".masterdiv" ).empty();
$("#masterdiv div").text("");
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();

Categories