Is there a native way, no jQuery, to check if a dom element has the attribute with the selected value. For example:
//assume doc has
data-mod="do" defined
This will be true:
document.hasAttribute('data-mod');
but this will be false:
document.hasAttribute('data-mod="do"')
Is there any way to natively check for a data attribute on a DOM element with the value?
You have to access the attribute's value via getAttribute and compare it to your expected string:
if (node.getAttribute('data-mod') === 'do') {
...
}
For modern browsers you can use matches:
if (node.matches('[data-mod="do"]')) {
...
}
… or for [data-*] attributes you can use dataset:
if (node.dataset.mod === 'do') {
...
}
You can do it properly with dataset,
if (elementNode.dataset['mod'] == 'do') {
//your code goes here.
}
By using dataset you can access the data-attributes of an element easily.
Yes, here it goes:
var selector = document.getElementsByTagName("H1")[0]; //Exemple of a h1
if (selector.getAttribute('data-mod') == "do"){
//Do your logic
}
This may work...
var list = document.querySelectorAll('[data-mod="do"]');
You could use Element.attributes
function data(el, dataName, dataValue) {
for (var i = 0; i < el.attributes.length; i++) {
if (/^(data)(?=-\w+|=[^=]*$|=$|$)/g.test(el.attributes[i].name)) {
if (dataName && el.attributes[i].name === "data-" + dataName) {
if (dataName && dataValue
&& el.attributes[i].name === "data-" + dataName
&& el.attributes[i].value === dataValue) {
return true
}
return true
} else {
return true
}
}
}
return false
}
var elems = document.querySelectorAll("div");
for (var i = 0; i < elems.length; i++) {
console.log(data(elems[i]))
}
var _name = "prop", _value = "123";
console.log("element #"
+ elems[1].id
+" has `data-*` attribute name:"
+_name
+", value:"+_value
, data(elems[1], _name, _value))
<div data="abc">abc</div>
<div id="prop" data-prop="123">123</div>
<div>no data</div>
Related
I have the following code which get all the data in kendo grid column Type. how can I check if array contain Type ='Custom Document'?
I tried the following
function chkCustomDocumentIncluded() {
var messageText = '';
var arrayType = [];
var data = $("#CustomDocumentsGrid").data("kendoGrid").dataSource._data;
for (i = 0; i < data.length; i++) {
arrayType.push(data[i].Type);
}
if (arrayType.includes("Custom SBA")) {
messageText = '#Localizer["Custom document is required"].Value';
}
return messageText;
}
console.log(arrayType) returns expected value but how can i add a condition to check the value exist?
Use the Array.every method to check if every element of the array meets a condition.
function chkCustomDocumentIncluded() {
var data = $("#CustomDocumentsGrid").data("kendoGrid").dataSource._data;
if (!data || data.every(d => d.Type == "Custom SBA")) {
return '#Localizer["Custom document is required"].Value';
} else {
return '';
}
}
This function match sets an attribute (collapsed) to true or false depending on
the value of a string :
function match(children) {
var data = $scope.treeData
for (var i = 0; i < data.length; i++) {
var s = data[i]
for (var i2 = 0; i2 < s.children.length; i2++) {
var s2 = s.children[i2]
for (var i3 = 0; i3 < s2.children.length; i3++) {
for (var i4 = 0; i4 < s2.children[i3].children.length; i4++) {
var text = "";
if ($scope.searchText == undefined) {
text = ""
} else {
text = $scope.searchText
}
if (s2.children[i3].children[i4].label
.toLowerCase() === text.toLowerCase()) {
s2.children[i3].collapsed = false
}
}
}
}
}
}
Excluding the bad use of variable names i3,i2 etc is there a cleaner method ?
As the inner most loop requires access to the outer loop can recursion still be used ?
Update :
Data structure :
[{"label":"test","collapsed":false,"children":[{"label":"test","collapsed":false,"children":[],"$$hashKey":"002"}],"$$hashKey":"001"}]
Update 2 :
Using a recursive function but the string 'test' is not being matched :
http://jsfiddle.net/U3pVM/19196/
fiddle src :
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
</div>
</div>
function TodoCtrl($scope) {
var json = [{"label":"test","collapsed":false,"children":[{"label":"test","collapsed":false,"children":[],"$$hashKey":"002"}],"$$hashKey":"001"}]
var searchText = 'test'
function match(node, searchText){
angular.forEach(node.children, function(idx, child){
node.collapsed = child.label.toLowerCase === searchText.toLowerCase
console.log(node.collapsed)
if(child.children.length > 0){
match(child, searchText);
}
});
}
match(json, searchText);
}
Please try this :
function match2(obj) {
if (obj.children) {
for (var i = 0; i < obj.children.length; i++) {
match2(obj.children[i]);
}
}
else {
var text = $scope.searchText ? $scope.searchText : "";
if (obj.label
.toLowerCase() === text.toLowerCase()) {
obj.collapsed = false
}
}
Your JSFiddle is very nearly there. I made a couple of changes for this working JSFiddle.
First, you were passing an array into match and not an object. I changed your json variable to be json instead by removing the outer [], but you could also have fixed this by passing in json[0].
The other change was that you had the two parameters, child and idx, were the wrong way round.
function match(node, searchText){
angular.forEach(node.children, function(child, idx){
node.collapsed = child.label.toLowerCase === searchText.toLowerCase
console.log(node.collapsed)
if(child.children.length > 0){
match(child, searchText);
}
});
}
Here's another way of doing it, using some:
function match (node, searchText) {
node.collapsed = node.children.some(function(child) {
return child.label.toLowerCase === searchText.toLowerCase;
});
angular.forEach(node.children, function(child, idx){
match(child, searchText);
})
}
I think something like this may work for you. I don't know anything about angular there might be something there that would make it easier.
var searchText = ($scope.searchText == undefined) ? "": $scope.searchText;
match($scope.treeData, searchText);
function match(node, searchText){
$.each(node.children, function(idx, child){
node.collapsed = child.label.toLowerCase === searchText.toLowerCase
if(child.children.length > 0){
match(child, searchText);
}
});
}
There is a little problem with this code:
function getParameters() {
var searchString = document.getElementById('input1').value,
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
console.log(hash);
//return hash;
if(val[0] == "class"){ //alert(val[1]);
$.each(hash, function( attribute, value ) {
test_div.setAttribute(attribute,value);
});
}
else if(val[0] == "color"){ //alert(val[1]);
$.each(hash, function( attribute, value ) {
test_div.style[attribute]=value;
});
}
monitor_test_div.innerText = ccc.innerHTML;
}
Depending by the order in which the parameters are inserted, they are repeated or dont work...
style a div using escaped URL parameters
Demo: JSFiddle 1
Demo: JSFiddle 2
I would like to obtain this:
Example 1:
input:
opacity=0&src=link1&color=red&color=green&src=link2&height=200
output:
<div src="link2" style="color: green;"></div>
Example 2:
input:
src=link1&color=red or color=red&src=link1
output:
<div src="link1" style="color: red;"></div>
in your line
if(val[0] == "class")
you are only checking the first element in your val array.
what you would want to do, is iterate through all the hash objects and simply check the attribute like this:
function getParameters() {
var searchString = document.getElementById('input1').value,
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
console.log(hash);
//return hash;
$.each(hash, function( attribute, value ) {
if(attribute=="color"){
test_div.style[attribute]=value;
}
else if(attribute=="src"){
alert(attribute);
test_div.setAttribute(attribute,value);
}
});
}
here is a working FIDDLE
Maybe you want something like this:
var test_div = $('#test_divs_id');
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
var key = unescape(val[0]);
var val = unescape(val[1]);
switch(key) {
case 'class': // treat 'class' key by ...
test_div.addClass(val); // ... adding the value as a class
break;
case 'src': // treat 'src' key,
case 'href': // treat 'href' key, maybe more ...
test_div.attr(key, val); //... by adding as an attribute with value
break;
default: // all other keys...
test_div.css(key, val); // ... are assumed css style names with value
break;
}
EDIT: Extended the switch with the examples + possibly more attributes
$("tr[class*='nowrap']").filter(function () {
return $("#DS_coords")
.val()
.indexOf(
$(this)
.find("td:eq(2)")
.text()
.match(/\d{1,3}\|\d{1,3}/)
) != -1;
}).find("input[id*='editInput']")
.val("huidigenaam")
.next("input")
.click();
})
This piece of code works. However, I want to change "huidigenaam" in a variable called huidigenaam, which I want to get like this:
if ($(this).find("td:eq(0)").text().indexOf("sometext") < 0) {
var huidigenaam = $(this).find("td:eq(0)").text() + "someteext"
}else{
var huidigenaam = $(this).find("td:eq(0)").text();
}
$(this) should be the "tr[class*='nowrap']" (so if my filter matches, also get the .text() from the first td in the tr. But I can't get it to work.
$("tr[class*='nowrap']").each(function() {
if ($(this).find("td:eq(0)").text().indexOf("Ausfake") < 0) {
var huidigenaam = $(this).find("td:eq(0)").text() + "Ausfake";
}else{
var huidigenaam = $(this).find("td:eq(0)").text();
}
$(this).filter(function () {
return $("#DS_coords").val().indexOf($(this).find("td:eq(2)").text().match(/\d{1,3}\|\d{1,3}/)) != -1;
}).find("input[id*='editInput']").val(huidigenaam).next("input").click();
})
})
I need to remove certain images with a specific src:
http://ukn.cs-mtc.com/wp-content/plugins/download-monitor/page-addon/thumbnail.gif
Is there a way to remove the whole <img> tag with JavaScript?
I had some free time (and a strange urge to write some JavaScript...), so I thought I'd offer this functional approach:
function removeNeighbour(el, elType) {
if (!el) {
return false;
}
else if (el.nextElementSibling) {
var nxt = el.nextElementSibling;
}
else {
var nxt = el.nextSibling;
while (nxt.nodeType !== 1 && nxt.nextSibling) {
nxt = nxt.nextSibling;
}
}
if (elType && nxt.tagName.toLowerCase() == elType.toLowerCase()) {
nxt.parentNode.removeChild(nxt);
}
else if (!elType) {
nxt.parentNode.removeChild(nxt);
}
}
function clearElsWithAttrEquals(el, attr, val, andNeighbour, neighbourType) {
if (!el || !attr || !val) {
return false;
}
else if (document.querySelectorAll) {
var matchingElems = document.querySelectorAll(el + '[' + attr + '="' + val + '"]'),
neighbourType = neighbourType || '';
for (var i = matchingElems.length - 1; i >= 0; i--) {
if (andNeighbour === true) {
removeNeighbour(matchingElems[i], neighbourType);
}
matchingElems[i].parentNode.removeChild(matchingElems[i]);
}
}
else {
var matchingElems = document.getElementsByTagName(el),
len = (matchingElems.length - 1);
for (var i = len; i >= 0; i--) {
if (matchingElems[i][attr] == val) {
matchingElems[i].parentNode.removeChild(matchingElems[i]);
}
}
}
}
clearElsWithAttrEquals('img', 'src', 'http://ukn.cs-mtc.com/wp-content/plugins/download-monitor/page-addon/thumbnail.gif', true, 'p');
JS Fiddle demo.
Quick guide to (and the only documentation I'm ever likely to write for) clearElsWithAttrEquals() function:
clearElsWithAttrEquals(el, attr, val[, andNeighbour[, neighbourType]]);
el : (string) identifies the element type ('img','p','span'...).
attr : (string) identifies which attribute you want to search by ('id', 'src', etc...)
val : (string) this will only match if the value is exactly equal to the string
andNeighbour : (Boolean, optional) do you want to remove the neighbouring element too? Pass true (if yes) or false (if not).
neighbourType : (string, optional) remove the neighbour only if it's of this element-type ('div','hr','span', etc) ; if omitted then the next sibling element will be removed regardless of its type.
References:
document.querySelectorAll() (Compatibility).
nextElementSibling (Compatibility).
nextSibling (Compatibility).
node.nodeType (Compatibility).
parentNode (Compatibility).
removeChild() (Compatibility).
String.toLowerCase().
while (condition) {/*...*/}.
Do you use jQuery? If so,
$('img[src="http://ukn.cs-mtc.com/wp-content/plugins/download-monitor/page-addon/thumbnail.gif"]').remove(); should work.
Otherwise...
var img = document.getElementsByTagName('img');
for(var i=0,i<img.length;i++) {
if(img[i].src == 'http://ukn.cs-mtc.com/wp-content/plugins/download-monitor/page-addon/thumbnail.gif') {
img[i].parentNode.removeChild(img[i]);
}
}
This can be done easily with jQuery:
$('img[src="<path>"]').remove();