JQuery discovers that all elements with a custom attribute begin with, get the remaining name and value

Say we have an element with a custom attribute

... bind-html="varName" ...

I want to find all elements with an attribute starting with "bind-",

then get the second part of this name, which is unknown, in this case "html".

And finally get the value "varName".

How did I achieve this with jQuery? I do not want to use the second attribute to describe attibute to bind (e.g., .. bind="varName" attr="html" ..)

+4
source share
4 answers

this.attributes name value.

:

$("input").each(function() {
    $.each(this.attributes, function() {
        if (this.name.indexOf('bind-') == 0) {
            console.log(this.name + ' has the value: ' + this.value);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input bind-koby='hello'>
<input bind-douek='stack'>
<input will-not-show='yes'>
<input bind-hello='overflow'>
Hide result
+1
<div class="bindable" data-bind="html:varName1"></div>
<div class="bindable" data-bind="css:varName2"></div>
<div class="bindable" data-bind="js:varName3"></div>
<div class="bindable" data-bind="whatEver:varName4"></div>

(function(){
  let bindables = $('.bindable');
  bindables.each(function(){
  let bindData = $(this).data('bind');
  let bindDataArray = bindData.split(":");
  console.log(bindDataArray);
 });
}());

u u want

+1

You can get all the elements and their attributes that they contain bind-using jquery .propertiesand .indexOf(), as shown in the following example.

// $("*") selects all elements in your html
$("*").each(function() {
  $.each(this.attributes, function() {
    // checks whether element has an attribute starts with "bind-" or not
    if(this.specified && this.name.indexOf("bind-") !== -1) {
        console.log("Attr Name: "+ this.name + " Attr Value: " + this.value)
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span bindNot-html="bindNot">element1</span>
<div bind-html="varName1">element2</div>
<a bind-html2="varName2">element3</a>
<div bind-html3="varName3">element4</div>
<span bindNot-html="bindNot">element5</span>
Run codeHide result
+1
source

ok what are you looking like

<div bind-html="varName">hi there i am </div>

ok hi this is me

var namer = $(" *[attr*='bind']").text();
console.log(namer);
0
source

Source: https://habr.com/ru/post/1683580/


All Articles