JS:
this.par = $(this).find("p");
HTML:
<p></p>
The problem is that I dont want to find p tag, but rather a div with a specific ID like this one below.
<div id="abc"></div>
Use the ID selector:
var myDivObj = $("#abc");
Take a look at the list of jQuery selectors.
Additional Information:
It's difficult to tell by your code what you're trying to do, but based on what you've posted, there is no reason to use $(this). The ID selector alone should meet your needs.
Well, you can just use the id selector:
$(this).find('#abc');
Since ids should be unique on the page, you may as well just use it as the constructor:
$('#abc');
If this isn't exactly the same, you're doing something wrong.
this.par = $(this).find("#abc");
You don't want to do that. Don't add properties to the html elements. This is better:
var par = $(this).find('#idOfElement')
Storing the result in this.par is a very bad idea, since this refers to a DomElement.
What you might be looking for is jQuery .data():
$(this).data('par', $(this).find('#idOfElement'))
Which allows you to associate #idOfElement with this.
use id selector
this.par = $(this).find("#abc");
but id is uniqe you can remove $(this).find and use this code
this.par = $("#abc");
Related
Hi I'm rewriting a script from jQuery to pure JS and I don't know how else could i write this.I want to get attribute of element inside class 'form-basket' with id 'przecenajs' I know getElementsByClassName returns object of elements, and that's probably why I get the error:document.getElementsByClassName(...).getElementById is not a function
but I'm not into JS that much so i might be wrong
price = document.getElementsByClassName('form-basket').getElementById("przecenajs").getAttribute("data-procent");
That because getElementsByClassName returns a HTMLCollection object.
You probably want to use querySelector function:
document.querySelector('.form-basket #przecenajs')
console.log(document.querySelector('.form-basket #przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
or
document.getElementById('przecenajs')
console.log(document.getElementById('przecenajs').getAttribute("data-procent"));
<div class='form-basket'>
<div id='przecenajs' data-procent="Hello!">
</div>
</div>
Resources
document.querySelector()
Document.getElementsByClassName()
You do not have to select the form-basket first. Since IDs should only be used once inside a document, you can simply selct by id like so:
document.getElementById("przecenajs").getAttribute("data-procent");
I assume you are searching for more than only one tag, because if you wouldn't you could just use document.getElementById() so I think these lines do the job you want, you have to manually create the list with all the attributes to replicate the jquery behaviour:
var priceList = [];
document.querySelectorAll(".form-basket #przecenajs").forEach( (element) =>{
priceList.push(element.getAttribute("data-procent"));
});
I have an element that contains an input text, to get the input text I'm using the jQuery method find.
The input text has a class name like this page-id-x with the x is variable, so I want to select that number after the substring page-id, and this is what I tried :
var id = ui.item.find('input').attr('class').split(/\s+/).filter(function(s){
return s.includes('page-id-');
})[0].split('-')[2];
console.log(id);
I think this code is too complicated, but I couldn't figure out some other way to do it.
If someone knows a better way, I'll be thankful.
Thanks in advance.
I'm going to assume the x part of page-id-x, not the id part, is what varies (since that's what your code assumes).
Another way to do it is with a regular expression, but I'm not sure I'd call it simpler:
var id = ui.item
.find('input')
.attr('class')
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
Example:
var ui = {
item: $("#item")
};
var id = ui.item
.find('input')
.attr("class")
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
console.log(id);
<div id="item">
<input class="foo page-id-23 bar">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above makes the same assumptions your current code does, which are:
The first input in ui.item is the one you want
It will have the relevant class name
I assume those are okay, as your question is asking for an alternative, suggesting what you have is working.
As you're using jQuery, take a look at this: https://api.jquery.com/category/selectors/attribute-selectors/
For your case, you can use $('[class^="page-id-"'). These types of selectors (listed on the link above) actually work in CSS, too. (At least most should, if not all.)
To get the number after page-id-, my suggestion would be to store that number in some other HTML attribute, like data-pageID="1" or the like.
So you could have:
<div id="page-id-3" data-pageID="3">CONTENT</div>
Then, when you have the DOM element using $('[class^="page-id-"'), you can access that number with .attr('data-pageID').val().
If you can control the HTML markup, instead of using class names, you can use data attributes instead. For example, instead of:
<input class="page-id-1">
You can use:
<input data-page-id="1">
Then jQuery can find this element effortlessly:
$('[data-page-id]').attr('data-page-id')
You can find your element using the *= selector.
let elem = document.querySelector('[class*=page-id-]')
Once you have the element, you can parse the id out:
let [base, id] = elem.className.match(/page-id-(\d+)/)
console.log('page id: %s', id);
When using jQuery and are using the .attr method as follows:
$(document).ready(function(){
$('.class1').click(function(){
id = $(this).attr('.class2');
});
});
Say I have the following HTML for the above function:
<div class="class1 $class2"></div>
The second class is attributed at runtime, so I have 10 divs, each with class1, but several with class2. Then I wish to use the jQuery function at the top, so that whenever I click on any of the divs, it applies the specific class2 of that div, to the variable ID.
I hope this makes more sense.
Since your class2 comes from your PHP code, you seem to hit the usecase of data-attributes.
With data-attributes you can easily have some extra data (often used for javascript purposes) on your HTML elements without having to use special classes or ids for that.
It works like that:
<span data-hero="batman">I'm a Bat!</span>
Where in your Javascript (using jQuery) you get the value of it by simply doing:
$('span').data('hero');
Refer to the MDN and the jQuery documentation for further information.
Is this what you're trying to do?
$(document).ready(function(){
$('.class1').click(function(){
var id = $(this).attr('class').replace('class1','').trim();
});
});
If you have a multi class tag this mean the HTML code would be like this:
<sometag class="class1 class2">...</sometag>
I think the simplest approach is to do some string operations on the class attribute of the tag:
var class2 = $(selector).attr("class").split(" ")[1];
OR you can write a simple jQuery plugin to do the work for you:
(function($){
$.fn.secondClass = function(){
var c = this.attr("class").split(" ");
if(c.length >= 2)
return c[1];
};
}(jQuery))
Usage: var class2 = $(selector).secondClass();
Hope this helps.
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
In my js I have a var in which I have stored innerHTML.
The var is having value something like
<h2>headline</h2>
<div>....</div>
...........
Now I want to retrieve value of h2 tag..what I am doing is
$(myvar).find("h2").text()
but its not working...what should be the exact syntax?
EDIT:
alert(myvar)=<h2>headline</h2>
<div>....</div>
Thanks.
The find method will not work for this case, because it gets the descendants of each element in the current set of matched elements (the h2 and the div in your example).
You can simply use filter (available on jQuery 1.3.2):
var myvar ="<h2>headline</h2>" +
"<div>....</div>";
alert($(myvar).filter('h2').text()); // headline
Check an example here.
Find() returns a collection of nodes. Use first():
h2text = $(myvar).first("h2").text();
Change your HTML to something like this.
<div>
<h2>headline</h2>
<div>....</div>
</div>
generally would make more sense to wrap the contents of your var in a div as proposed by ChaosPandion.
if that's not possible, you can try this...
<script>
var myVar = '<h2 id="test">heading</h2><div>stuff</div>';
var jVar = $(myVar);
alert($(jVar.get(0)).text());
</script>