1

For some reason… I can't get this simple get method to work. I'm using data attribute to find out where the meta html is located on the server.

var i = 0;


while (i < 1) {
  $('body').find('.div[data-meta]').each(function() {
    var $this = $(this)
    var meta = $this.getAttribute("data-meta")

    $.get(meta, function(data) {$('head').append(data);});
    i++;
  });
}
<div class="div" data-meta="meta.html"></div>
Monwell Partee
  • 708
  • 7
  • 16
  • 1
    If you are only running the while loop once, you don't need the while loop. – Terry Aug 03 '17 at 13:31
  • 1
    To start, add `;` after `var $this = $(this)` and `var meta = $this.getAttribute("data-meta")` – Hamza Abdaoui Aug 03 '17 at 13:31
  • 1
    Offtopic: @HamzaAbdaoui meh - makes no difference to anything – freedomn-m Aug 03 '17 at 13:34
  • 3
    Check your console, you'll see: `$(...).getAttribute is not a function` - you're mixing your jquery objects with DOM nodes. Either use `var meta = this.getAttribute("data-meta")` *or* `var meta = $(this).data("meta")`. Learn to use the browser console / debugger. Check what value you get for `var meta` - that's where the issue is, not the `get`. – freedomn-m Aug 03 '17 at 13:36
  • The reason why I use while is because at one point… I got it to work some how, but it kept running indefinitely and crashed my computer and lost how I did it because it didn't save. – Monwell Partee Aug 03 '17 at 13:43
  • But with the while condition… I know it'll only run once – Monwell Partee Aug 03 '17 at 13:44
  • I have no clue what I did to make it work… I accidentally typed something… and it magically worked – Monwell Partee Aug 03 '17 at 13:45

1 Answers1

2

var i = 0;

$(function(){
$('body').find('.div[data-meta]').each(function() {
  var meta = $(this).data('meta');
  console.log(meta)
  });
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div" data-meta="meta.html"></div>

it works... try it now.

Neeraj Pathak
  • 759
  • 4
  • 13
  • 1
    Please add some comments to describe what you've changed and why it works / why the original did not work. https://meta.stackoverflow.com/questions/300837/what-comment-should-i-add-to-code-only-answers – freedomn-m Aug 03 '17 at 13:37
  • For completeness: `var meta = $this.attr("data-meta");` (jQuery) also works, as does `var meta = this.getAttribute("data-meta");` (pure javascript) – Adder Aug 03 '17 at 13:40