jQuery selector for data attribute array - javascript

Theres' this html code:
<div class="wcpa_form_outer" data-attrrelated="["wcpa-select-1658734650073"]">
for which i'm trying to append html to it. I have tried various approaches but none have worked.
jQuery('.wcpa_form_outer[data-attrrelated="["wcpa-select-1658734650073"]"]').append('some html here');
or
jQuery('.wcpa_form_outer[data-attrrelated="[wcpa-select-1658734650073]"]').append('some html here');
or
jQuery('.wcpa_form_outer').data('attrrelated').append('some html here');
any clues?

The " and/or [] in the attribute value may be the problem Remove it, or try using a part (the most relevant part?) of the attribute value:
$('[data-attrrelated*="1658734650073"]')
.append('some html here!');
$('[data-attrrelated*="wcpa-select-165873465007"')
.append('<br>some html here too!');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wcpa_form_outer" data-attrrelated="["wcpa-select-1658734650073"]"></div>

Problem is that you're using the HTML Entity " in your attribute. This is being translated to a literal quote. JQuery does not do Entity translation, so it's literally looking for the string ["wcpa-select-1658734650073"] with ampersands and all, not ["wcpa-select-1658734650073"] which is the actual value in your attribute.
You can work around this by using one of the following methods (after also translating the Entity into a quote in your code).
Use a CSS "contains" selector for your attribute ( attr*=value ) (demonstrated by KooiInc's answer) or
Use a string template which will allow you to embed both types of quotes in your string and get an exact match ( attr=value ), shown below
Constructing a string value containing quotes by using string concatenation (e.g. '["' + value + '"]' )
Use the decodeEntities function from this answer to translate your attribute value before attempting the lookup (untested, and it's 10 years old)
jQuery(`.wcpa_form_outer[data-attrrelated='["wcpa-select-1658734650073"]']`).append('foo')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wcpa_form_outer" data-attrrelated="["wcpa-select-1658734650073"]">append here:
</div>

Related

Escape Double Underscore and $ symbol with vanilla javascript using querySelectorAll

I'm trying to target certain HTML tags generated by a framework, basically I'm trying to aim for the attributes and their values but since the framework auto generate them they have really weird naming. I can't target classes because there are multiple tags with the same class names.
In order to target this element:
<div class="jx_ui_html_div" __jx__id="___$_90__nav_bar">
I'm trying:
let chatNavBar = document.querySelectorAll('[__jx__id="___$_90__nav_bar"]')
When I console log "chatNavBar" I'm getting and empty object.
I know that i have to escape some characters on the attribute value and name but I just can't figure out how, any help will be really appreciate it.
Here's a snippet of what I'm trying to aim here:
let chatNavBar = document.querySelectorAll('[__jx__id="___$_90__nav_bar"]')
console.log("Selected Element:" + '' + JSON.stringify(chatNavBar))
<div class="jx_ui_html_div" __jx__id="___$_90__nav_bar">
<p>Hellow World</p>
<div>
Or on CodePen
The class of this element is just : "jx_ui_html_div"

Removing HTML elements with special characters

I want to remove HTML DOM object by its ID, that contains special characters(dots, commas etc). I tried to use this code that escapes those characters but it's not working (element its not being removed):
var file_html_id ="#"+ filename.replace(/[!"#$%&'()*+,.\/:;<=>?#\[\\\]^`{|}~]/g, "\\\\$&");
console.log(file_html_id);
$(file_html_id).remove();
where filename its the ID. It's worth to mention that string with escaped characters is displayed as expected. And if I "hardcode" that string it works fine... So where the problem might be?
Instead of trying to escape the characters yourself you could try a couple of other ways:
Use jQuery's escapeSelector() on the id string. This will escape any special characters in the string. Note escapeSelector was added in v3.0 of jQuery. View how they are doing the escaping here
if interested.
$( '#'+ $.escapeSelector('theText') )
Use an attribute selector instead of trying to escape all the possible characters for an id selector
$('[id="idHere"]')
This however will select multiple elements if for some bizarre reason you have multiple elements with the same id.
Demo
var id = "some,weird®,id";
var id2 = "some,other®,id";
$('#'+ $.escapeSelector(id2) ).css({border:'1px solid green'});
$('[id="'+id+'"]').css({border:'1px solid red'});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div id="some,weird®,id"></div>
<br/>
<div id="some,other®,id"></div>

Generating id selector dynamically based on user-input

I am facing a problem in jQuery selector. I am generating selector string dynamically based on user-input as show below :-
jQuery("#" + userInput + "-edit").modal("show")
When the user enters value like "AdvancedResults." Selector becomes
jQuery("#AdvancedResults.-edit").modal("show")
which does not return expected element, despite the fact that
Am I doing something patchy ? Is there any better way to solve this problem ?
Btw, apologising for newbie question, as I am new to JS world.
Thanks in advance.
Just use:
Use the escaping rules from the jQuery selectors API as follows:
$("#AdvancedResults\\.-edit").modal("show");
You can replace . to \. dynamically using str.replace():
var str = "AdvancedResults.";
str = str.replace(/\./g, "\\."); // it will add add \\ dynamically before .
console.log($("#"+str+'-edit').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input id="AdvancedResults.-edit" type="text"/>
If your element does have an id #AdvancedResults.-edit, that is, includes a dot, you must escape it with \\ as stated in the docs jQuery Selectors
Use [attribute=""] selector in such cases where the parameter is dynamic and might contain special chars not supports by jQuery # - ID selector.
jQuery("[id='" + userInput + "-edit']").modal("show")
Example snippet :
var userInput = "abc.";
alert(jQuery("[id='" + userInput + "-edit']").val())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="abc.-edit" value="test"/>
I have solved it using attribute hack.
It's as follow :-
jQuery("[id='" + userInput + "-edit']").modal("show");
It worked perfectly for me.

How to extract content of html tags from a string using javascript or jquery? [duplicate]

This question already has answers here:
Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
(29 answers)
Closed 8 years ago.
Maybe this is very basic, but I am all confused.
I have a simple html page with many sections (div). I have a string containing html tags in javascript. The code is as follows:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
var str1="<html><body><div id='item1'><h2>This is a heading1</h2><p>This is a paragraph1.</p></div><div id='item2'><h2>This is a heading2</h2><p>This is another paragraph.</p></div><div id='lastdiv'>last</div></body></html>";
</script>
</head>
<body>
<div id="title1"></div>
<div id="new1"></div>
<div id="title2"></div>
<div id="new2"></div>
</body>
</html>
I want to extract content of the html tags (from the string in javascript) and display that content in my html page in desired sections.
i.e. I want "This is a heading1" displayed in <div id="title1"> and "This is a paragraph1." to be displayed in <div id="new1"> and same for the second pair of tags.
I need all of this to work only on the client side. I have tried to use HTML DOM getElementByTagName method and its getting too complicated. I know very little of jquery. And I am confused. I dont understand how to go about it. Can you guide me what to use - javascript or jquery and how to use it? Is there a way to identify the from the string and iterate through it?
How to extract "This is heading1" (and similar contents enclosed in the html tags) from str1?? I don't know the index of these hence cannot use substr() or substring() function in javascript.
Using .text() as both a 'getter' and a 'setter' we can just repeat the pattern of:
target the element on the page we wish to fill
give it content from
the string
jsFiddle
<script type="text/javascript">
var str1="<html><body><div id='item1'><h2>This is a heading1</h2><p>This is a paragraph1.</p></div><div id='item2'><h2>This is a heading2</h2><p>This is another paragraph.</p></div><div id='lastdiv'>last</div></body></html>";
$(function(){
var $str1 = $(str1);//this turns your string into real html
//target something, fill it with something from the string
$('#title1').text( $str1.find('h2').eq(0).text() );
$('#new1').text( $str1.find('p').eq(1).text() );
$('#title2').text( $str1.find('h2').eq(1).text() );
$('#new2').text( $str1.find('p').eq(1).text() );
})
</script>
IMHO , You can do this in jquery in two steps :
Step 1) Parse the string into an XML/HTML document.
There are at least two ways to do this:
a) As mentioned by Sinetheta
var htmlString = "<html><div></div></html>";
var $htmlDoc = $( htmlString );
b) Using parseXML
var htmlString = "<html><div></div></html>";
var htmlDoc = $.parseXML( htmlString );
var $htmlDoc = $( htmlDoc );
Please refer http://api.jquery.com/jQuery.parseXML/
Step 2) Select text from the XML/HTML document.
var text = $htmlDoc.text( jquery_selector );
Please refer http://api.jquery.com/text/
Well,
First of all you should clarify how you are getting the source html from your own html. If you are using Ajax you should tick the source as html, even xml.
document.getElementById('{ID of element}').innerHTML
if use jquery
$('selector').html();
<div id="test">hilo</div>
<script>
alert($('#test').html());
<script>
Let me preface my answer with the knowledge that I don't think I fully understand what you want to do...however I think you want to replace some (although you make it sound like all) html with some data source.
I've rigged a simple example is jsfiddle here:
http://jsfiddle.net/rS2Wt/9/
This does a simple replace using jquery on a target div.
Hope this helps, good luck.

I have a problem with slash in javaScript n Ajax

I have a problem with slash in javaScript n Ajax
I am displaying value dynamically in a span like below:
String num = "37-C110PDD/L";
<span id="p21stk_<%=NUM%>"></span>
in Script:
value for chks[0] is 37-C110PDD/L here the value contains slash and is not displaying the required value in span
Code used in script to update value dynamically:
$("#p21stkArwhed_"+chks[0].value).html($("#qohArrVal_"+chks[0].value).val())
Above code working for parameters without SLASH
Any idea how to solve....?
Thank you..........
Using slashes in the attribute ID is illegal.
See What are valid values for the id attribute in HTML?
You should replace your slash with a valid character, an hyphen ("-") or an underscore ("_") for example.
You can use custom data-* attributes (http://www.w3.org/TR/html5/elements.html#embedding-custom-non-visible-data-with-the-data-attributes), for example:
HTML:
<span data-id="37-C110PDD/L">a span</span>
JS:
alert( $("span[data-id='37-C110PDD/L']").text() );

Categories