How to select an item by attribute without jquery? - javascript

I need select element like this: $('[data-key=' + objectId + ']'), but i need select this without jquery, using document.querySelector or something else on pure JS.

You can do it with document.querySelectorAll('[data-key=' + objectId + ']') and loop through all results
var allKeys = document.querySelectorAll('[data-key=' + objectId + ']');
[].forEach.call(allKeys, function(elem){
console.log(elem); //Do your stuff with each element
});

You can try this
<p data-test="testquery">
document.querySelectorAll('[data-test]')

Related

why wouldn't this selector work? JS

I have a class name active
and in js I have something like this
var selectClass = active;
var a = $("'." + selectCLass + "'");
a.on('click', function(){})
When I do this, it would keep on giving me errors.
What am I missing here?
Generated selector string has errors... make it like
var a = $("." + selectCLass);

Fetch html of a tag by id with slash [duplicate]

In html code I am using code
<input type = "text" id = "abc#def.com"> to get text
now it need to get its value which is entered in text field. I am using jquery to do that:
$( document ).ready( function() {
$( ".bid" ).click( function() {
idVal = this.id
bidID = "#" + idVal + "bid"
spanID = "#" + idVal + "cbid"
bidValue = $(bidID).val();
alert(idVal)
alert(bidID)
alert(bidValue) //this alert says undefined
$( spanID ).html( ' ' ).load( '{% url online_machines %}?id=' + idVal + '&bidvalue=' + bidValue);
});
});
By doing this i get the value error undefined.
I tried to remove special characters from the id to get its value. But I need the id with special characters. How can
I get its value using jquery ?
Instead of trying for ID using #, try this to match attribute like this,
$('[id=ID]')
or
$('[id='+ID+']')
so instead of
bidID = "#" + idVal + "bid"
you can try
bidID = "[id=" + idVal + "bid]"
Try escaping it:
$('#abc\\#def.com').val();
First paragraph of http://api.jquery.com/category/selectors/
It looks like JQuery has a useful method for this as of version 3 called escapeSelector.
$('#' + $.escapeSelector(my_id_with_special_chars));
https://api.jquery.com/jQuery.escapeSelector/
$(document.getElementById('abc#def.com')) also works.
Use the function CSS.escape() to select that DOM element.
In your case for the id abc#def.com you can use the below code.
$("#" + CSS.escape('abc#def.com'));
Have a shot at this, not 100% on whether this is what you're after. Let me know:
$( document ).ready(function() {
$(".bid").click(function() {
idVal = $(this).attr('id');
bidID = "#" + idVal + "bid";
spanID = "#" + idVal + "cbid";
bidValue = bidID.val();
alert(idVal);
alert(bidID);
alert(bidValue);
spanID.html(' ').load('{% url online_machines %}?id=' + idVal + '&bidvalue=' + bidValue);
});
});
This solution below worked for me, it is pretty clean:
//your HTML id has special characters:
var option= "Some option with (parenthesis or # )";
//use this type of jquery query:
$(`[id="order_${option}"]`).prop('checked',true)

Replace selected text inside p tag

I am trying to replace the selected text in the p tag.I have handled the new line case but for some reason the selected text is still not replaced.This is the html code.
<p id="1-pagedata">
(d) 3 sdsdsd random: Subject to the classes of this random retxxt wee than dfdf month day hello the tyuo dsds in twenty, the itol ghot qwerty ttqqo
</p>
This is the javascript code.
function SelectText() {
var val = window.getSelection().toString();
alert(val);
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/\r?\n|\r/g,""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(/[^\x20-\x7E]/gmi, ""));
$('#' + "1-pagedata").html($('#' + "1-pagedata").text().replace(val,"textbefore" + val + "textAfter"));
}
$(function() {
$('#hello').click(function() {
SelectText();
});
});
I have also created a jsfiddle of the code.
https://jsfiddle.net/zeeshidar/w50rwasm/
Any ideas?
You can simply do $("#1-pagedata").html('New text here');
Since your p doesn't content HTML but just plain text, your can use both html() or text() as getter and setter.
Also, thanks to jQuery Chaining you can do all your replacements in one statement. So, assuming your RegExp's and replacement values are correct, try:
var $p = $('#1-pagedata');
$p.text($p.text().replace(/\r?\n|\r/g,"").replace(/[^\x20-\x7E]/gmi, "").replace(val,"textbefore" + val + "textAfter"));

Dynamic selector

I am trying to do this:
var divString = '#sContainer' + [index];
$(divString).append(SSDisplay);
So that it is
var divString = '#sContainer' + [index];
$('#sContainer0').append(SSDisplay);
$('#sContainer1').append(SSDisplay);
$('#sContainer2').append(SSDisplay);
It doesn't seem to be working. I have also tried
$('#sContainer' + [index]).append(SSDisplay);
Any idea how I can get the jquery selector to do this dynamically?
You are repeatedly appending the same SSDisplay.
Try:
$('#sContainer' + index).append( SSDisplay.clone(true) );

how to refresh the list in jquery javascript

Hi i m having one page with one textbox named search and one search button. When i'm searching anything for the first time it's showing me the right data but when i'm searching some other things for the next time then the elements which was listed before are also appended below of that new list. Suppose i'm searching state name by k it will give me right list of karnataka, kerala. But if i start to search again by g, it will show me in output as goa,gujrat,karnataka kerala. i tried using refresh option but it still not working. This is my js code
$.each(response.state, function (i, state) {
$('#statelist').append(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});
$("#statelist").listview("refresh");
and this is html
You are using .append() function. It appends whatever you append to the end of the list.
Check this link:
http://api.jquery.com/append/
Try using innerHTML property of the DOM model.
You could add
If(!('#statelist').html() == ""){
$(this).remove();
//execute rest of code that appends state list
}
Then do an else statement and execute your append code without removing()
UPDATE: a better option is to do this-
$.each(response.state, function (i, state) {
$('#statelist').html(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});

Categories

Resources